Preparing publication-quality figures in R with mo

2019-08-27 22:39发布

问题:

This question already has an answer here:

  • Saving grid.arrange() plot to file 5 answers

I have quite a specific problem with producing 300ppi plots in tiff format for publication. I have found ggsave to work beautifully with a single plot, which can then be exported to GIMP to compress the resulting large tiff file. However, it seems to run into trouble when plotting two figures next to each other, e.g.

plot1<-ggplot(.........)
plot2<-ggplot(.........)
grid.arrange(plot1, plot2, ncol=2)

ggsave(filename = "Figure 1.tiff", scale = 1, width = 10, height = 5, 
       units = "cm", dpi = 300)

This results in only plot2 appearing in the resulting tiff file, with plot 1 nowhere to be seen.

I will also have a figure which does not use ggplot, but consists of three plots produced with barplot2 and matplot, but presumably this faces a similar problem. Essentially, could anyone suggest a way of translating what appears in the plot appearing in the plot window (I use RStudio) to a high-resolution tiff file with as little fuss as possible?

回答1:

I recently had the same issue and I could not find a ready made solution, I ended up creating a wrapping function for a list of ggplot objects that tries to plot the entries on a kind of balanced grid.

'plotP' <- function (P){
  # P is a list of plots
  require(gridExtra)
  N <- length(P)
  Ncol <- ceiling(sqrt(N))
  Nrow <- ceiling(N/Ncol)
  grid.newpage()
  pushViewport(viewport(layout=grid.layout(Nrow, Ncol)))
  row <- 1
  col <- 1
  for (i in 1:N){
    print(P[[i]], vp=viewport(layout.pos.row=row, layout.pos.col=col)) 
    col <- col + 1
    if (col > Ncol){
      col <- 1
      row <- row + 1
    }
  }
}

Now you can plot the figures in one command and save the device

plotP(list(plot1, plot2))
name <- 'grid-of-plots'
height <- 6
width <- 8
dpi <- 300
dev.copy(tiff, paste0(name, ".tiff"), width = width*dpi, height =height*dpi)
try(dev.off(), silent = TRUE)#close window

hope it helps,

kind greetings