Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

force a regular plot object into a Grob for use in grid.arrange

b <- ggplot(cars,aes(x=speed,y=dist))+geom_line()
grid.arrange(
    b,
    plot(cars),
    ncol=1
)

gives me 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"

Let's assume my second graph has to come out of the plot function. How would one convert that output to a grob-like object so it plays nicely with grid.arrange ?

like image 844
Chapo Avatar asked Nov 20 '15 12:11

Chapo


People also ask

What is a Grob in Ggplot?

First off a grob is just short for “grid graphical object” from the low-level graphics package grid; Think of it as a set of instructions for create a graphical object (i.e. a plot). The graphics library underneath all of ggplot2's graphical elements are really composed of grob's because ggplot2 uses grid underneath.

What is a Grob?

A grid graphical object (“grob”) is a description of a graphical item. These basic classes provide default behaviour for validating, drawing, and modifying graphical objects.

What package is grid arrange in R?

grid. arrange() function sets up a gtable layout to place multiple grobs on a page. It is located in package "gridExtra".

What does the gridExtra package allow you to do?

5 The gridExtra package. The gridExtra package provides useful extensions to the grid system, with an emphasis on higher-level functions to work with grid graphic objects, rather than the lower-level utilities in the grid package that are used to create and edit specific lower-level elements of a plot.


1 Answers

you can try with gridGraphics

library(gridGraphics)

grab_grob <- function(){
  grid.echo()
  grid.grab()
}

plot(cars)
g <- grab_grob()
b <- ggplot(cars,aes(x=speed,y=dist))+geom_line()
grid.arrange(
  b,g,
  ncol=1
)

or, alternatively, use gridBase.

like image 101
baptiste Avatar answered Oct 13 '22 02:10

baptiste