【问题标题】:aesthetic mapping in ggplot inside loopggplot内部循环中的美学映射
【发布时间】:2014-09-18 21:47:37
【问题描述】:

我试图使用 ggplot2 在单个图中绘制多个时间序列连续变量。由于有很多变量,我尝试在 for 循环中使用正常的美学映射,

p1<-ggplot(df, aes(x=timVar))
ind<-c(2,4,5,6,8,9,10,12,13,15,17) # Index of the series that I wanted to plot
for(i in ind){
    p1<-p1+geom_line(aes(df[,i]))
}
print(p1)

因为这只给了我上一个系列的情节,所以我搜索了一些解决方案,最后找到了一个建议我使用 aes_string() 函数的解决方案。我将代码重建为,

p1<-ggplot(df, aes(x=timVar))
ind<-c(2,4,5,6,8,9,10,12,13,15,17) # Index of the series that I wanted to plot
for(i in ind){
    p1<-p1+geom_line(aes_string(names(df)[i]))
}
print(p1)

这给了我需要的所有台词。但是,当我尝试为每个变量获取单独的颜色时,我无法获得离散的颜色。我使用了以下代码,

p1<-p1+geom_line(aes_string(names(df)[i], col=names(df)[i]))

有没有办法在循环中同时使用 aes_string 和 aes,或者有没有办法生成带有标签的离散颜色值作为变量名。

【问题讨论】:

  • 我不知道你为什么要这么做。你能提供你的df吗?
  • 您是否有不想将数据集重塑为长格式的原因?有关示例,请参见 this answer

标签: r loops for-loop ggplot2 aesthetics


【解决方案1】:

我正在使用dplyr 包的melt 函数。它解决了我上面的所有问题。谢谢你们所有的cmets。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    相关资源
    最近更新 更多