Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use empty space produced by facet_wrap?

I have a faceted plot that forms an n x m grid. By design, the last (bottom-right) cell is always empty, so I'd like to utilize the extra space by adding another ggplot object. My current solution relies on low-level viewport approach, which is not very elegant and requires some hard-coding for position and size.

Instead, I assume the empty space is reachable in some other fashion, probably with gridExtra?

Here's a minimal example for n=m=2. Note that the edges are not aligned properly, so some extra work is required to manually adjust viewport's parameters, which is a pain, especially if (n, m) change afterwards.

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

like image 422
tonytonov Avatar asked Mar 17 '14 09:03

tonytonov


1 Answers

You can use gtable to access the "empty cell" like so

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: generic placement for n x m facets

like image 65
Rosen Matev Avatar answered Sep 17 '22 15:09

Rosen Matev