【问题标题】:Arranging multiple ggplot2 plots排列多个 ggplot2 图
【发布时间】:2011-08-29 11:42:34
【问题描述】:

我正在尝试创建很多想要以网格形式显示的图(简单的 x-y 条形图)。当我使用 gridExtra 包的 grid.arrange 时,随着地块数量的增加,每个单独的地块都会缩小。有没有办法创建绘图画布,使其跨越多个页面而不缩小每个单独的绘图?

gridExtra 的一个简单例子:

require(ggplot2)
require(gridExtra)
plots = lapply(1:50, function(.x) qplot(1:10,rnorm(10),main=paste("plot",.x)))
do.call(grid.arrange,  plots)

上面的代码生成了 50 个图,但它们被缩小以适合画布。有没有办法避免这种情况?即,让它们跨越多个页面,每个页面将有大约 9 个左右的图?我可以接受 PNG 或 PDF 文件格式。

在尝试 grid.arrange 之前,我使用了这个站点的代码示例:http://gettinggeneticsdone.blogspot.com/2010/03/arrange-multiple-ggplot2-plots-in-same.html 并遇到了同样的问题。

我还没有尝试将不同的数据框组合成一个带有绘图标识符的巨型数据框。然后我正在考虑使用情节标识符进行构面,但我不确定它是否也会出现缩小每个情节的相同问题。

希望我的问题很清楚......

谢谢, -e

【问题讨论】:

  • 你能分面吗?您可以以九个为一组创建一个新的 faceting 变量,并从中制作一个多页 pdf。
  • @Andrie,谢谢!我正在寻找错误的关键字,但没有发现该链接。使用 pdf() 并在循环内打印效果很好。我将把那个伪代码放在答案中。 @Chase,这是个好主意。对于我的情况,我没有将内容存储在数据框中,因此我只是将其直接打印到循环内的 pdf 中。如果我有一个汇总的数据框,你的建议会更好,因为我不需要 grid.arrange。谢谢!

标签: r ggplot2


【解决方案1】:
library(gridExtra)
library(ggplot2)
my_func = function (d,filename = "filename.pdf") {
    pdf(filename,width=14) # width = 14 inches
    i = 1
    plot = list() 
    for (n in names(d)) {
        ### process data for plotting here ####
        plot[[i]] = qplot(x, y, geom="bar", data = my_data,)
        if (i %% 9 == 0) { ## print 9 plots on a page
            print (do.call(grid.arrange,  plot))
            plot = list() # reset plot 
            i = 0 # reset index
        }
        i = i + 1
    }
    if (length(plot) != 0) {  ## capture remaining plots that have not been written out
        print (do.call(grid.arrange,  plot))
    }
    dev.off()
}

【讨论】:

    猜你喜欢
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 2019-05-24
    • 2023-03-29
    • 2014-12-02
    • 1970-01-01
    • 2016-10-20
    相关资源
    最近更新 更多