在R

时间:2016-12-21 08:30:32

标签: r pdf for-loop ggplot2 gridextra

请假设任何数据集。情况:我在所有自变量上运行for循环,以创建与因变量的关系(散点图)。并希望将这些图保存为pdf,但是1页或2页pdf表示1个文件,而不是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(示例)发布图表。我非常感谢所有的帮助。谢谢你!

1 个答案:

答案 0 :(得分:1)

一种简单的方法可能是将数据转换为长格式(使用gather中的tidyr),然后使用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")

给出:

enter image description here

如果出于某种原因,你真的想要遍历这些图,你可以使用包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)

给出:

enter image description here

如果不是传说的话会有效。幸运的是,这些也很容易处理

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

给出

enter image description here