首页 > 解决方案 > R ggplot,循环内有变量

问题描述

我的循环中的 ggplot 有问题。我创建了一个带有 colnames 的向量,我想将其作为 ay 变量循环,但显然有问题,因为 ggplot 函数似乎将它作为字符串而不是我的数据框中的 colname。

这是我的 df :

> head(nbf2020)
  Plant annee rang bloc genotype feuilles9.06 feuilles21.06 feuilles12.07
1    19  2020    A    1    22928           10            16            23
2    20  2020    A    1    25899           12            18            25
3    21  2020    A    1    27819            8            15            25
4    22  2020    A    1    25699           19            24            25
5    23  2020    A    1    24882           11            19            29
6    24  2020    A    1    23948           21            29            39
  feuilles3.08 feuilles19.08 repetition total
1           26            NA          1     5
2           29            NA          1     2
3           31            NA          1     3
4           40            NA          1     2
5           35            NA          1     2
6           45            NA          1     5

我想为 col feuilles.XX 创建子图,然后我创建了一个带有 colnames 的向量:

> months = colnames(nbf2020[,c(6:10)])
> months
[1] "feuilles9.06"  "feuilles21.06" "feuilles12.07" "feuilles3.08" 
[5] "feuilles19.08"
> 

在我使用这个向量进行循环并创建 ggplot 之后:

for (i in months) {

  y_name = paste("number of leafs counted", i, sep="")
  print(i)
  temp_plot = ggplot(nbf2020, aes(x=bloc, y=i, colour=bloc,fill=bloc))+
  geom_boxplot(outlier.alpha = 0, alpha=0.25)+
  geom_jitter(width=0.25)+  
  stat_summary(fun=mean, colour="black", geom="point", 
               shape=18, size=3) +
  theme_classic()+
  theme(legend.position="none")+
  geom_text(data = myletters_df, aes(label = letter, y = 60 ), colour="black", size=5) + xlab("bloc number") + ylab(y_name) 

  ggsave(temp_plot, file=paste0(i, ".pdf", sep=""), width = 14, height = 10, units = "cm")
}

除了我的 y 值只是列的名称之外,它有点工作。

在此处输入图像描述

有谁知道出了什么问题?感谢您的帮助 !

标签: rggplot2

解决方案


由于您使用的是 variable i,它原来是一个字符串,所以请使用aes_string.aes


推荐阅读