How to use the white space created by facet_wrap?

I have a faceted graph that forms an nxm grid. By design, the last (lower right) cell is always empty, so I would like to use extra space by adding another ggplot object. My current solution is based on the low-level viewport approach, which is not very elegant and requires some hard coding in position and size.

Instead, I assume that white space is available in a different way, perhaps with gridExtra ?

Here is a minimal example for n=m=2 . Please note that the edges do not align properly, so some additional work is required to manually adjust the viewport settings, which is a pain, especially if (n, m) changes after that.

 library(ggplot2) library(grid) p <- qplot(displ, hwy, data = mpg[mpg$cyl != 5, ]) + facet_wrap(~ cyl, nrow=2) q <- qplot(date, unemploy, data = economics, geom = "line") + labs(x = NULL, y = NULL) p print(q, vp=viewport(0.75, 0.275, 0.45, 0.45)) 

enter image description here

+8
r ggplot2 gridextra facet grob
source share
1 answer

You can use gtable to access the "empty cell" this way

 library(gtable) pg <- ggplotGrob(p) qg <- ggplotGrob(q) pl <- gtable_filter(pg, 'panel', trim=F)$layout pg <- gtable_add_grob(pg, qg, t=max(pl$t), l=max(pl$l)) grid.newpage() grid.draw(pg) 

Edit: shared layout for nxm facets

+9
source share

All Articles