rlayoutscatter-plotr-carcowplot

Combining scatterplots


I am trying to combine multiple (four) scatter plots into one figure (but not a scatterplot matrix). I am making the individual scatter plots with the scatterplot() function of the car package. I used to be able to combine the four plots using either the layout() or par() function. However, now when I try to do this in Rstudio, it just displays the four plots sequentially. I'm not sure if this is because of the newer versions of R or Rstudio.

Here is an example using the mtcars dataset:

par(mfrow=c(2,2), oma=c(1,1,2,1), mar=c(4,4,0,1), cex.lab=1, cex.axis=0.8)

scatterplot(mpg ~ disp, data=mtcars, smooth=F, boxplots=F, xlab="", ylab="mpg", grid=F)

scatterplot(mpg ~ wt, data=mtcars, smooth=F, boxplots=F, xlab="", ylab="", grid=F)

scatterplot(hp ~ disp, data=mtcars, smooth=F, boxplots=F, xlab="hp", ylab="mpg", grid=F)

scatterplot(hp ~ wt, data=mtcars, smooth=F, boxplots=F, xlab="Weight", ylab="", grid=F)

I am running R 3.4.2, RStudio 1.1.453, on Windows 10. Any pointers would be appreciated.


Solution

  • You can try plot_grid from cowplot package. Note that cowplot requires R 3.5.0.

    Edit: to clarify, you need the development version of cowplot on GitHub

    devtools::install_github("wilkelab/cowplot")
    
    library(car)
    library(gridGraphics)
    library(cowplot)
    
    par(xpd = NA, # switch off clipping, necessary to always see axis labels
        bg = "transparent", # switch off background to avoid obscuring adjacent plots
        oma = c(1, 1, 2, 1), 
        mar = c(4, 4, 0, 1),
        mgp = c(2, 1, 0), # move axis labels closer to axis
        cex.lab  = 1, 
        cex.axis = 0.8
    ) 
    
    scatterplot(mpg ~ disp, data=mtcars, smooth=F, boxplots=F, xlab="", ylab="mpg", grid=F)
    rec1 <- recordPlot()  # record the previous plot
    
    scatterplot(mpg ~ wt, data=mtcars, smooth=F, boxplots=F, xlab="", ylab="", grid=F)
    rec2 <- recordPlot()
    
    scatterplot(hp ~ disp, data=mtcars, smooth=F, boxplots=F, xlab="hp", ylab="mpg", grid=F)
    rec3 <- recordPlot()
    
    scatterplot(hp ~ wt, data=mtcars, smooth=F, boxplots=F, xlab="Weight", ylab="", grid=F)
    rec4 <- recordPlot()
    
    plot_grid(rec1, rec2, rec3, rec4,
              labels = "AUTO", 
              hjust = 0, vjust = 1)
    

    enter image description here