0

The multiplot function is defined here in the cookbook

Consider the following graphs.

p1 = ggplot(mtcars,aes(y=mpg, x=cyl)) + geom_point()
p2 = ggplot(mtcars,aes(y=disp, x=cyl)) + geom_point()
multiplot(p1,p2, layout=matrix(1:2,nrow=1))

enter image description here

I'd like to manipulate (with function DoStuff) the plot as a gtable object rather than as a ggplot object.

g1 = ggplot_gtable(ggplot_build(p1))
g1 = DoStuff(g1)
g2 = ggplot_gtable(ggplot_build(p1))
g2 = DoStuff(g2)

I can print a gtable with grid.draw.

How can I modify the multiplot function, so that it also accepts gtable objects and not just ggplot objects?

Remi.b
  • 17,389
  • 28
  • 87
  • 168

1 Answers1

2

in my somewhat biased view you'd be better off using

gridExtra::grid.arrange(g1,g2, ncol=2)

but to answer your question:

change

print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
                                layout.pos.col = matchidx$col))

to something like

  if(inherits(plots[[i]], "gg")) {

    print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
                                    layout.pos.col = matchidx$col))

  } else if(inherits(plots[[i]], "gtable")) {

    pushViewport(viewport(layout.pos.row = matchidx$row, 
                          layout.pos.col = matchidx$col))
    grid.draw(plots[[i]])
    upViewport()
  }

and call it as before,

g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(p2)
multiplot(g1,g2, layout=matrix(1:2,nrow=1))
baptiste
  • 75,767
  • 19
  • 198
  • 294