How to use empty space produced by facet_wrap?

安稳与你 提交于 2019-11-26 16:18:25

问题


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))


回答1:


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



来源:https://stackoverflow.com/questions/22450765/how-to-use-empty-space-produced-by-facet-wrap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!