如何使用facet_wrap生成的空白空间? [英] How to use empty space produced by facet_wrap?

查看:186
本文介绍了如何使用facet_wrap生成的空白空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个分面图,形成一个 n x m 网格。按照设计,最后一个(右下角)单元总是空的,所以我想通过添加另一个ggplot对象来利用额外的空间。我目前的解决方案依赖于低级别的 viewport 方法,这不是很优雅,需要对位置和大小进行一些硬编码。

相反,我假设可以用其他方式获得空白空间,可能是 gridExtra

以下是 n = m = 2 的最简单示例。请注意,边缘没有正确对齐,因此需要额外的工作来手动调整视口的参数,这很痛苦,特别是如果(n,m)之后发生变化。 / b>

  library(ggplot2)
库(网格)
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))

解决方案

您可以使用 gtable 来访问空单元格 (g)
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))

gri d.newpage()
grid.draw(pg)

编辑: code> nxm 构面


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

解决方案

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

这篇关于如何使用facet_wrap生成的空白空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆