2

Take the following example:

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

The second line will open a graphics device but there is nothing in it. It will just stay open. I could close it simply with dev.off() or clicking the 'x'. However, I am interested in finding out how to prevent it opening in the first place. Is there a way? Or is ther another package that could do this without the device showing up?

Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
vanao veneri
  • 970
  • 2
  • 12
  • 31

2 Answers2

1

I don't know why the graphics device is showing up but I can point out some issues in your code and suggest an alternative way.

Your code returns NULL rather than storing the plots. You need to use the following approach (which is very troublesome) to store a plot object:

# 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

Let's say we managed to store 11 plots, the marrangeGrob(pl, nrow = 2, ncol = 2) command tries to arrange 4 objects (2 rows x 2 columns). You need to get rid of either nrow=2 or ncol=2.

My suggestion would be to use ggplot2 for more flexible and elegant plots in collaboration with grid.arrange, which doesn't open up the extra graphics window:

# 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)
OzanStats
  • 2,756
  • 1
  • 13
  • 26
1

I think I might have found the solution for you, I got it from this post Disable GUI, graphics devices in R

Put the following at the beginning of your script:

options(device=pdf)

The disadvantage though is that it creates a empyt pdf Rplots.pdf in your current working directory, but it prevents the graphic device from showing up.

mmoisse
  • 138
  • 2
  • 9