3

I have a fairly complex facet_wrap of choropleth maps that share a common legend and separating them into individual plots. I want to add another very simple bargraph into an unused facet area. I thought I could use annotation_custom as seen here:

https://github.com/hadley/ggplot2/wiki/Mixing-ggplot2-graphs-with-other-graphical-output

p = qplot(1:10, 1:10) + theme_bw()
g = ggplotGrob(qplot(1, 1))
p + annotation_custom(grob = g, xmin = 2, xmax = 7, ymin = 6, ymax = 10)

But this does not seem to size things correctly even when playing with x/y-min/max. It apprears to want to annotate on each facet. Not what I want.

Separating each facet into an individual plot and using gridExtra::grid.arrange would be difficult because of the shared gradient legend that each facet works together to generate.

plot1 <- ggplot(mtcars, aes(factor(mtcars$gear))) + 
    geom_bar() + 
    facet_wrap(~cyl, ncol=2) + 
    coord_flip()


plot2 <- ggplot(mtcars, aes(as.factor(am))) + 
    geom_bar(aes(fill=factor(cyl)))

This fails (plots on each facet):

g <- ggplotGrob(plot2)

plot1 + annotation_custom(grob = g, xmin = 0, xmax = 1, ymin = 0, ymax = 1)

Desired look:

enter image description here

Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519

1 Answers1

10
g1 <- ggplotGrob(plot1)
g2 <- ggplotGrob(plot2)

g1 <- gtable::gtable_add_grob(g1, g2, t = 8, l=7)
grid.newpage()
grid.draw(g1)
baptiste
  • 75,767
  • 19
  • 198
  • 294
  • +1000! I was trying to work this through with `ggplot_gtable` but this is way more elegant and succinct (and far more readable than mine would have been). – hrbrmstr Mar 22 '14 at 22:30
  • 1
    @batiste Works great. My actual problem was a wrap of 5 facets (2 columns) plus one empty. I read the documentation for `gtable_add_grob` but couldn't figure out what `t` and `l` were doing. For my circumstance I used `t = 12, l=7` but this info may be helpful to future searchers. – Tyler Rinker Mar 22 '14 at 22:47
  • 3
    You may check related Q&A [**here**](http://stackoverflow.com/questions/22450765/how-to-use-empty-space-produced-by-facet-wrap) with a slightly alternative use of `t` and `l`, where hardcoding seems to be avoided. – Henrik Mar 22 '14 at 22:54