0

I want to create four (largely identical) plots in R and combined into a single .png file to insert into a presentation.

I am using ggplot2.

I have to do a bit of data-wrangling first based on a single test value. Thus I have created a function (with the test value as the argument) and then assign the resulting figure to a figure object.

eg

Fig1 = RDDPlot('2010-05-02')
Fig2 = RDDPlot('2010-06-02')
Fig3 = RDDPlot('2010-07-02')
Fig4 = RDDPlot('2010-08-02')

I am trying to use par() as per: https://www.statmethods.net/advgraphs/layout.html and Multiple scatterplot figure in R

but all these example use plot and are done on a single line. I am building my plot up with multiple statements (eg combinations of scatterplot with vline, mean lines etc), so it is easier for me to assign to a figure object and then layout the objects in a (2,2).

The following does not work for me:

png(paste0(path,'Plot.png'),width=12.8,height=9.6,units="cm",res=1200)

  par(mfrow=c(2,2))
  Fig1
  Fig2
  Fig3
  Fig4

dev.off()

It just produces a .png with only Fig1 on it...

zx8754
  • 52,746
  • 12
  • 114
  • 209
brb
  • 1,123
  • 17
  • 40
  • Convenient programming solution after plotting the 4 figures but outside R is imagemagic – milan Nov 28 '19 at 05:41

1 Answers1

1

You can try to use grid.arrange from the package of gridExtra and then save the plot using ggsave:

library(gridExtra)
library(ggplot2)

p = grid.arrange(ncol = 2, nrow = 2, Fig1, Fig2, Fig3, Fig4)

ggsave(plot = p, filename = "Plot.png", units = "cm", height = 9.6, width = 12.8, dpi = 1200 )
dc37
  • 15,840
  • 4
  • 15
  • 32
  • That is perfect! Thank you so much. Any way of slightly reducing white space around them so that they look as big as possible? – brb Nov 28 '19 at 05:52
  • You can play with the argument `plot.margin` in the `theme` command. – dc37 Nov 28 '19 at 05:59
  • 1
    You can check here for the use of `plot.margin` https://stackoverflow.com/questions/15556068/removing-all-the-space-between-two-ggplots-combined-with-grid-arrange – dc37 Nov 28 '19 at 06:02
  • Thank you! Appreciate the link. I am an R newbie, so this cuts down my trial and error! Love SO people! Racing to finalise a presentation... – brb Nov 28 '19 at 06:05
  • Glad to be bale to help you. Good luck with the presentation – dc37 Nov 28 '19 at 06:07