从数据框列表中创建多个图 - 使用颜色(ggplot2)

时间:2015-07-31 00:10:23

标签: r ggplot2

我试图在ggplot2中创建9个折线图,每个折线图使用列表中每个数据框的数据(称为" my_list")。

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

但我需要额外的扭曲:每个地块上的线条需要有不同的颜色。

编辑 - 我明白了,请看下面的答案。

2 个答案:

答案 0 :(得分: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))

enter image description here

答案 1 :(得分:0)

我设法弄明白了,以为我分享了我所学到的东西。

# 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)
}