【发布时间】:2015-07-31 00:10:23
【问题描述】:
我正在尝试在 ggplot2 中制作 9 个折线图,每个折线图都使用列表(称为“my_list”)中每个数据框的数据。
我在这里找到了一个巧妙的解决方案: Making multiple plots from a list of data frames
但我需要一个额外的转折点:每个图上的线条需要具有不同的颜色。
编辑 - 我想通了,请参阅下面的答案。
【问题讨论】:
我正在尝试在 ggplot2 中制作 9 个折线图,每个折线图都使用列表(称为“my_list”)中每个数据框的数据。
我在这里找到了一个巧妙的解决方案: Making multiple plots from a list of data frames
但我需要一个额外的转折点:每个图上的线条需要具有不同的颜色。
编辑 - 我想通了,请参阅下面的答案。
【问题讨论】:
我认为定义一个包裹函数更容易,
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))
【讨论】:
我设法弄清楚了,我想我会分享我所学到的。
# 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)
}
【讨论】: