Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...