我想在这篇文章中做一些事情:R: saving ggplot2 plots in a list
问题是我无法让它发挥作用。我似乎能够得到单个图,但facet_wrap
抛出错误。我会满足于只输出所有图形,然后将它们作为jpg或其他东西保存到磁盘,所以我可以稍后滚动它们。
for(n in 1:5){
pdata <- data.frame(mt1[n])
library(ggplot2)
p <-ggplot(pdata, aes(x=variable, y=value, color=Legend, group=Legend))+ geom_line()+ facet_wrap(~ color)
}
链接到dput
数据:mt1
编辑: 添加了整个正确的文件,它有点长
答案 0 :(得分:3)
如果我们因数据框中缺少变量而忽略facet
错误,您可以使用ggsave
以这种方式生成并将图表保存在不同的文件中:
for(n in 1:5){
pdata <- data.frame(mt1[n]) # better to use mt1[[n]]
p <-ggplot(pdata, aes(x=variable, y=value, color=Legend, group=Legend))+ geom_line()
ggsave(paste0("plot",n,".jpg"), p)
}
一些改进建议:
首先,正如@Dason指出的那样,你的library(ggplot2)
电话应该在你的循环之外。
其次,如果您通过[.]
访问列表元素,那么结果仍然是列表。您应该这样做:[[.]]
,这将导致data.frame(.)
调用不必要(如上面代码中所述)。
第三是建议使用*apply
系列函数。在这里,使用lapply
。
在代码中总结所有这些要点:
require(ggplot2) # load package outside once
o <- lapply(seq_along(mtl), function(idx) {
p <- ggplot(mtl[[idx]], aes(x = variable, y = value,
color = Legend, group = Legend))+ geom_line()
ggsave(paste0("plot",idx,".jpg"), p)
})