Search code examples
rgrob

arrange R plots: how can I arrange plots of the VIM package?


I would like to generate multiple plots using marginplot() (VIM package) and then arrange them into one big figure. I tried to use grid.arrange (grid/gridExtra package) and it did not work. The error was, that a grob was expected as input. So I tried to first convert the marginplot into a ggplot (as.ggplot) or grob (as.grob) but this did not work. Has anyone an idea how to arrange the plots?

library(VIM)
library(ggplotify)
library(grid)
library(gridExtra)

x <- cars[, c("speed", "dist")]
marginplot(x)
y <- cars[, c("speed", "dist")]
marginplot(y)

p <- qplot(1,1)
#p2 <- as.ggplot(marginplot(x))
r <- rectGrob(gp=gpar(fill="grey90"))
grid.arrange( r, p,p, r, ncol=2)

I created a small code with cars, where I managed to arrange grey squares and qplots. put I cannot add the marginplot.


Solution

  • With base plots this error occurs. Learned here: grid.arrange from gridExtras exiting with "only 'grobs' allowed in 'gList'" after update

    grid.arrange is intended to be used with "grid graphical objects" (grobs), such as ggplot2.

    One could find an equivalent grid-plot or use a base-graphics approach to stacking plots. Try this:

    library(VIM)
    
    x <- cars[, c("speed", "dist")]
    y <- cars[, c("speed", "dist")]
    
    par(mfrow = c(2,2))
    marginplot(x)
    marginplot(y)
    plot(rnorm(100))
    hist(rnorm(100)) 
    par(mfrow = c(1, 1)) #reset this parameter
    

    enter image description here