【问题标题】:How to prevent marrangeGrob opening a graphics device如何防止marrangeGrob打开图形设备
【发布时间】:2018-10-31 17:28:54
【问题描述】:

举个例子:

library(gridExtra)
pl <- lapply(1:11, function(.x) plot(1:10, rnorm(10), main=paste("plot", .x)))
ml <- marrangeGrob(pl, nrow=2, ncol=2)

第二行将打开一个图形设备,但里面没有任何内容。它只会保持打开状态。我可以简单地使用 dev.off() 或单击“x”来关闭它。但是,我有兴趣首先了解如何防止它打开。有办法吗?或者是否有其他软件包可以在不显示设备的情况下执行此操作?

【问题讨论】:

    标签: r ggplot2 gridextra


    【解决方案1】:

    我不知道为什么会显示图形设备,但我可以指出您代码中的一些问题并提出替代方法。

    您的代码返回 NULL 而不是存储图。需要使用下面的方式(很麻烦)来存储一个plot对象:

    # set seed for reproducibility
    set.seed(147)
    
    plot.new() # clears the previous plots 
    plot(1:10, rnorm(10), main = "test") # creates a scatter plot
    p <- recordPlot() # stores the plot
    p # accesses the plot
    

    假设我们设法存储了 11 个图,marrangeGrob(pl, nrow = 2, ncol = 2) 命令尝试排列 4 个对象(2 行 x 2 列)。您需要摆脱 nrow=2ncol=2

    我的建议是使用ggplot2grid.arrange 协作获得更灵活和优雅的绘图,这不会打开额外的图形窗口:

    # import packages
    library(ggplot2)
    library(gridExtra) # for grid.arrange
    
    # simple wrapper to create multiple plots
    my_ggplot <- function(no, x = 1:10, y = rnorm(10)) {
      ggplot(mapping = aes(x, y)) + 
        geom_point() + 
        labs(title = paste("MY GGPLOT", no), x = "x-axis label", y = "y-axis label")
    }
    
    # build and store the plots
    p1 <- my_ggplot(1)
    p2 <- my_ggplot(2)
    p3 <- my_ggplot(3)
    p4 <- my_ggplot(4)
    
    # arrange the plots in a grid with 2 colums
    grid.arrange(p1, p2, p3, p4, ncol = 2)
    

    【讨论】:

      【解决方案2】:

      我想我可能已经为你找到了解决方案,我从这篇帖子Disable GUI, graphics devices in R得到它

      将以下内容放在脚本的开头:

      options(device=pdf)
      

      虽然缺点是它会在您当前的工作目录中创建一个 empyt pdf Rplots.pdf,但它会阻止图形设备显示。

      【讨论】:

        猜你喜欢
        • 2013-03-26
        • 1970-01-01
        • 1970-01-01
        • 2021-07-20
        • 2019-10-14
        • 2019-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多