【问题标题】:Making multiple plots from a list of data frames - with colors (ggplot2)从数据框列表中制作多个图 - 使用颜色 (ggplot2)
【发布时间】:2015-07-31 00:10:23
【问题描述】:

我正在尝试在 ggplot2 中制作 9 个折线图,每个折线图都使用列表(称为“my_list”)中每个数据框的数据。

我在这里找到了一个巧妙的解决方案: Making multiple plots from a list of data frames

但我需要一个额外的转折点:每个图上的线条需要具有不同的颜色。

编辑 - 我想通了,请参阅下面的答案。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我认为定义一个包裹函数更容易,

    dl = replicate(5, data.frame(x=1:10, y=rnorm(10)), simplify = FALSE)
    
    plot_fun = function(d, col) {
           ggplot(d, aes_string(x="x",y="y")) + geom_line(col=col) +
             theme()
    }
    
    pl = mapply(plot_fun, d = dl, col = palette()[1:5], SIMPLIFY=FALSE)
    
    # interactive use
    gridExtra::grid.arrange(grobs=pl)
    
    ## save to a device
    ggsave("plotstosave.pdf", gridExtra::arrangeGrob(grobs=pl))
    

    【讨论】:

    • 您好,有什么关于即时保存地块的建议吗?谢谢
    【解决方案2】:

    我设法弄清楚了,我想我会分享我所学到的。

    # first create a vector with the colors you want
    colors = c("red", "blue", "green", "purple", "cyan", "orange", "teal", "pink", "maroon") 
    
    # then loop through the colors in geom_line (as opposed to doing it in the ggplot aes, that gave me lines of the same color every time).
    
    for(i in 1:length(my_list))
    {
        df1 = as.data.frame(my_list[[i]])
        plotdf1 <- ggplot(df1, aes(x=x, y=y)) +
                   geom_line(size=1,color=colors[i])
        print(plotdf1)
    }
    

    【讨论】:

      猜你喜欢
      • 2014-03-01
      • 1970-01-01
      • 2018-05-21
      • 1970-01-01
      • 2020-08-24
      • 1970-01-01
      • 2014-06-18
      • 1970-01-01
      相关资源
      最近更新 更多