【问题标题】:Save grid.arrange output in loop and print to word (ReporteRs) or PDF files循环保存 grid.arrange 输出并打印到 word (ReporteRs) 或 PDF 文件
【发布时间】:2018-03-09 05:20:41
【问题描述】:

我已检查此链接中列出的解决方案: Saving grid.arrange() plot to file 但无法将其应用于我的问题,解决方案尚不清楚。

我有一个循环,它为每个 i 创建四个图,然后将它们排列在 grid.arrange 中:

    for (i in 1:n)){
p1<- ggplot(predictors, aes(x = x1, y = x2)) + geom_point()
p2<- ggplot(temp) + geom_histogram(aes(x=value)) + 
  facet_grid(. ~ variable, scales = "free_x") 
p3<- ggplot(predictors_trans) + geom_point(aes(x = trans.x1, y = trans.x2))
p4<- ggplot(temp) + geom_histogram(aes(x=value), data = temp) + 
  facet_grid(. ~ variable, scales = "free_x")

###arrange plots in grid:
plot_list[[i]] =  (grid.arrange(p1, p2, p3, p4))

###write grid to doc via ReporteRs package
mydoc2 = addPlot( doc = mydoc2, fun = print, x = plot_list[[i]], 
    vector.graphic = TRUE, par.properties = parCenter(), width = 6, heigth = 

###save all images to directory as well
ggsave(filename=paste("myplot",i,".jpg",sep=""), plot_list[[i]])

     }

plots生成并保存,但是生成的word文档在mydoc2写入后为空:

writeDoc( mydoc2, "why224.docx")
browseURL( "why224.docx" )

我还尝试只将图像写入 PDF,结果为空:

pdf("plots61.pdf")
for (i in 1:n) {
             print((plot_list[[i]]))
             }
dev.off()

如果我删除x=plot_list[[i]] 并在addPlot 命令中设置x=grid.arrange(p1,p2,p3,p4),我会得到一个带有空白图像的word 文档:

有没有人有关于如何将 grid.arrange 对象或循环的 ggsave 结果打印到文档(word 或 pdf)的任何解决方案?谢谢。

【问题讨论】:

    标签: r ggplot2 ms-word reporters


    【解决方案1】:

    ggsave 一起使用arrangeGrob。此循环为每次迭代将网格保存到单独的 pdf:

    library(ggplot2)
    library(gridExtra)
    for(i in 1:4) {
        p1 <- qplot(1, 1, geom = "point")
        p2 <- qplot(1, 1, geom = "point")
        p3 <- qplot(1, 1, geom = "point")
        p4 <- qplot(1, 1, geom = "point")
        g <- arrangeGrob(p1, p2, p3, p4)
        ggsave(file = paste0("myplot", i, ".pdf"), g)
    }
    

    【讨论】:

    • 非常感谢,您知道如何将循环的每次迭代中的所有绘图保存到一个 PDF 或最好是 word 文档吗?
    • 我的解决方案不是将它们保存为 pdf 吗?我不明白你的意思。
    • 嗨,是的,这确实保存到 pdf,但每个都保存到相应的 pdf,有没有办法将所有循环输出保存到一个 pdf?
    猜你喜欢
    • 2012-04-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2021-03-24
    • 2021-08-23
    • 2011-12-19
    • 2020-07-28
    • 2010-12-13
    相关资源
    最近更新 更多