5

This question builds from a related post which shows how to easily store a plot as an r object with the %<a-% function from the pryr package. Great! However, I now want to create a multiplot that combines a base r plot with 2 ggplot figures. I am using grid.arrange below.

Using the base r cars data I can make two ggplot figures.

library(ggplot2)
library(pryr)
library(gridExtra)

Fig1 <- qplot(speed, data=cars, geom="histogram")
Fig2 <- qplot(dist, speed, data=cars, geom="point")

I then make a figure with plot, and save the figure as an object using the %<a-% function from the pryr package. Slick.

Fig3 %<a-% plot(cars$speed, cars$dist)
Fig3

Lastly, I want to combine the 3 figures into a single plot as shown below.

Figs <- grid.arrange(Fig1, Fig2, Fig3,
                     layout_matrix = rbind(c(1,1,1,2,2), c(1,1,1,2,2), c(3,3,3,3,3)))

The code produces the following error:

Error in gList(list(grobs = list(list(x = 0.5, y = 0.5, width = 1, height = 1,  : 
  only 'grobs' allowed in "gList"

How can I save an base r plot to be combined with additional ggplot figures?

Community
  • 1
  • 1
B. Davis
  • 3,391
  • 5
  • 42
  • 78
  • Seems like you should be using the accepted answer on that linked question, not the `% – MrFlick Mar 10 '17 at 16:27
  • @MrFlick oh, I see now. I was not fully understanding the accepted answer to the linked post. Indeed, using the `gridGraphics` approach works. Do you want to post an answer or should I remove the question as it is a bit superfluous...? – B. Davis Mar 10 '17 at 16:38
  • 1
    If you have code that makes your example work, I'd recommend answering your own question below because it could be useful to others. – MrFlick Mar 10 '17 at 16:41

1 Answers1

6

As correctly noted by @MrFlick, the accepted answer linked here is a better approach than the %<a-% function which does not store a grid.

The code below produces the desired result.

library(ggplot2)
library(gridExtra)
library(gridGraphics)
library(grid)

Fig1 <- qplot(speed, data=cars, geom="histogram")
Fig2 <- qplot(dist, speed, data=cars, geom="point")

plot(cars$speed, cars$dist)
grid.echo()
Fig3 <- grid.grab()

Figs <- grid.arrange(Fig1, Fig2, Fig3,
                     layout_matrix = rbind(c(1,1,1,2,2), c(1,1,1,2,2), c(3,3,3,3,3)))
Community
  • 1
  • 1
B. Davis
  • 3,391
  • 5
  • 42
  • 78
  • I followed your answer to solve my question [here](https://stackoverflow.com/q/46261833/3766430) without success. Any suggestions? I want to produce a multiplot using the graphs created from `plot`. – Enigma Sep 21 '17 at 13:05