【问题标题】:ggplot works in individual code but not work in loopggplot 在单独的代码中工作,但不能在循环中工作
【发布时间】:2021-05-04 13:31:48
【问题描述】:

我在循环中遇到 ggplot 问题。 单独使用效果很好。

如下:

*plotgg<-
  ggplot(renewalplot, aes(x = Month,y=Rate)) +
    stat_summary(fun = mean, na.rm = TRUE,geom="bar")+
    labs(x = "Month") +
  ggtitle("Rate Change Distribution")+
  theme(axis.text.x = element_text(angle = 90, hjust = 1))+
  facet_grid(cols = vars(Year))
print(plotgg)*

当我把它们放在循环中时,它给了我错误:

vars <- colnames(detailinfo_renewal_1)
varslist1 = vars[c(13)]


for (i in varslist1) {
  renewalplot <- detailinfo_renewal_1 %>%
    filter(Product=="FI") 
  
  plotgg<-
    ggplot(renewalplot, aes(x = renewalplot[, i],y=Rate)) +
    stat_summary(fun = mean, na.rm = TRUE,geom="bar")+
    labs(x = i) +
    ggtitle("Mean of Rate Change Distribution")+
    theme(axis.text.x = element_text(angle = 90, hjust = 1))+
    facet_grid(cols = vars(Year))
  print(plotgg)
  
  
}

非常感谢! 液晶

【问题讨论】:

  • 错误是“不知道如何为 tbl_df/tbl/data.frame 类型的对象自动选择比例。默认为连续。is.finite(x) 中的错误:未实现默认方法对于类型“列表””
  • 请使用dput 或我们可以复制和使用的东西添加数据。了解how to ask a good questionhow to give a reproducible example

标签: r ggplot2


【解决方案1】:

您在进入循环时所做的更改会告诉您很多错误可能出在哪里:

aes(x = renewalplot[, i],y=Rate)

这种绘制美学的方法行不通。通常,当您选择美学时,会将美学的名称传递给x 的值,例如x = Month。在幕后,ggplot() 然后从您的数据源中找出适当的值。

另一种映射美学的方法是使用aes_string(),它可能更适合您的用例。由于i 已经是作为字符串的列名,所以它正好适合

for (i in varslist1) {
  renewalplot <- detailinfo_renewal_1 %>%
    filter(Product=="FI") 
  
  plotgg<-
    ggplot(renewalplot, aes_string(x =  i, y = "Rate")) +
    stat_summary(fun = mean, na.rm = TRUE,geom="bar")+
    labs(x = i) +
    ggtitle("Mean of Rate Change Distribution")+
    theme(axis.text.x = element_text(angle = 90, hjust = 1))+
    facet_grid(cols = vars(Year))
  print(plotgg)
  
  
}

【讨论】:

  • 谢谢迈克尔。何时使用 aes,何时使用 aes_string。
  • 问题是使用那个aes_string,它解决了变量问题,但是对于y变量它不起作用所以如何......
  • 当您想将参数作为字符串而不是名称(即带引号)传递时,您可以使用aes_string()
【解决方案2】:

你可以写一个函数:

library(dplyr)
library(ggplot2)

plot_fn <- function(col) {
  renewalplot <- detailinfo_renewal_1 %>% filter(Product=="FI") 
  
  ggplot(renewalplot, aes(x = .data[[col]],y=Rate)) +
    stat_summary(fun = mean, na.rm = TRUE,geom="bar")+
    labs(x = col) +
    ggtitle("Mean of Rate Change Distribution")+
    theme(axis.text.x = element_text(angle = 90, hjust = 1))+
    facet_grid(cols = vars(Year))
}

并使用lapply 将其应用于varslist1 中的每个值。

list_plot <- lapply(varslist1, plot_fn)

【讨论】:

  • 谢谢罗纳克。太棒了,它有效!实际上,我只需要将“aes(x =renewplot[, i],y=Rate)”更改为“aes(x =.data[[i]],y=Rate)”。请问,什么时候用dataframe[,i],什么时候用dataframe[[i]]?
  • .data 是一个特殊关键字,当您将列名作为字符串传递时使用(如此处)。我不记得有任何用例可以随时使用dataframe[,i]
  • 您好 Ronak,我可以邀请您回答另一个我没有提出的问题,因为您知识渊博。谢谢....stackoverflow.com/questions/59313161/…
猜你喜欢
  • 2016-12-21
  • 1970-01-01
  • 2020-08-25
  • 2013-10-29
  • 1970-01-01
  • 2021-05-25
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
相关资源
最近更新 更多