【问题标题】:Saving Multiple graphs in 1 pdf page from a for loop in R从 R 中的 for 循环将多个图形保存在 1 个 pdf 页面中
【发布时间】:2017-05-06 14:42:18
【问题描述】:

请假设任何数据集。情况:我正在对所有自变量运行 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(示例)的形式发布图表。我非常感谢所有帮助。在此先感谢!

【问题讨论】:

    标签: r pdf for-loop ggplot2 gridextra


    【解决方案1】:

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

    给予

    【讨论】:

    • 非常感谢,真的很有帮助。你能告诉我如何在同一解决方案中使用 aes_string 时使用 y= log(y),因为“thispredictor”作为 x 传递,我必须使用 aes_string
    • 您应该能够以与您相同的方式键入它,只是在引号内。在我的示例中,您只需使用y = "log(Sepal.Width)"。您还可以使用粘贴(或其他返回字符向量的函数)来添加函数,例如,paste0("log(",thisPredictor, ")")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 2022-01-01
    • 2023-03-29
    相关资源
    最近更新 更多