请假设任何数据集。情况:我正在所有自变量上运行 for 循环,以创建与因变量的关系(散点)图。并希望将绘图保存为 pdf 文件,但保存在 1 个文件的 1 或 2 页 pdf 中,而不是将每个图形保存在 1 个单独的页面中(我已经实现了)。我正在使用以下案例
第一次尝试使用开发选项
library(ggplot2)
library(gridExtra)
pdf("one.pdf", onefile = TRUE)
for (i in 1:length(dataset))
{
new_plot[[i]]=print(ggplot(data=dataset, aes(x=dataset[[i]], y=loss))+geom_point(size=1, alpha=0.3)+
geom_smooth(method = lm)+
xlab(paste0(colnames(int[i]), '\n', 'R-Squared: ',round(cor(int[[i]],int$loss, use = 'complete.obs'), 2)))+
ylab("log(loss)") + theme_light())
plot_list = c(new_plot[[i]])
grid.arrange(plot_list)
}
dev.off()
第二次尝试使用 ggsave
for (i in 1:length(dataset))
{
new_plot[[i]]=print(ggplot(data=dataset, aes(x=dataset[[i]], y=loss))+geom_point(size=1, alpha=0.3)+
geom_smooth(method = lm)+
xlab(paste0(colnames(int[i]), '\n', 'R-Squared: ',round(cor(int[[i]],int$loss, use = 'complete.obs'), 2)))+
ylab("log(loss)") + theme_light())
m=marrangeGrob(new_plot[[i]],nrow=2, ncol=2)
}
ggsave("one.pdf",m)
两次我都收到错误
Error in gList(data = list(list(x = c(2213.18, 1283.6, 3005.09, 939.85, :
only 'grobs' allowed in "gList"
如果可能的话,请分享如何在每个页面上以 2*2(示例)形式发布图表。我非常感谢所有的帮助。提前致谢!
最佳答案
一种简单的方法可能是将数据转换为长格式(使用 tidyr
中的 gather
),然后仅使用 facet_wrap
进行排列为你。这也节省了一些困难的循环,并自动包含您可能需要/想要的任何图例。
因为您没有提供任何可重现的数据,所以这里是一个带有内置 iris
数据的示例。
iris %>%
gather(Response, Value, -Sepal.Width, -Species) %>%
ggplot(aes(x = Value
, y = Sepal.Width
, col = Species)) +
geom_point() +
geom_smooth(method = "lm") +
facet_wrap(~Response
, scale = "free_x")
给出:
如果出于某种原因,您确实想循环遍历绘图,则可以使用包 cowplot
将内容拼接在一起。上述方法的问题之一是,您似乎每次都会重写绘图列表,而您最好构建所有绘图,然后处理它们。
在这里,我使用 lapply
而不是 for
,因为它往往工作得更顺利。我还使用 aes_string
而不是将向量传递给 aes
,因为这样可以更清楚地了解发生的情况。
myPlots <- lapply(names(iris)[c(1,3,4)], function(thisPredictor){
iris %>%
ggplot(aes_string(x = thisPredictor
, y = "Sepal.Width"
, col = "Species")) +
geom_point() +
geom_smooth(method = "lm")
})
然后,您可以使用 plot_grid
将它们像这样放在一起
plot_grid(plotlist = myPlots)
给出:
如果不是传奇的话,这会起作用。幸运的是,这些也可以轻松处理
plot_grid(
plot_grid(plotlist = lapply(myPlots, function(x){x + theme(legend.position = "none")})
, nrow = 1)
, get_legend(myPlots[[1]] + theme(legend.direction = "horizontal"))
, nrow = 2
, rel_heights = c(9,1) )
给出
关于r - 通过R中的for循环将多个图表保存在1个pdf页面中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41258300/