将空图添加到ggplot2中的facet_wrap

时间:2015-05-21 11:26:25

标签: r ggplot2

我正在尝试创建3个图,其中所有面板应该具有相同的大小,所以我认为解决方案可能是facet_wrap。我的问题是,我不想在每个

中使用相同数量的图表
df <- data.frame(group=c(1,1,2,2,2,3,3),
                 name=c('a','b','c','d','e','f','g'),
                 x=c(1,2,3,4,5,6,7),
                 y=c(2,3,4,5,6,7,8))
ggplot(df, aes(x,y)) + geom_point() + facet_wrap(~ name, ncol=3)

结果将图表组合成一个连续的顺序,但我想按照我的组列对它们进行分组。

所以我期望的结果是

a b _
c d e 
f g _

但我得到的是

a b c
d e f
g _ _

有没有人建议像这样创建一个图表,可能是通过添加空图表?我找到了另一个帖子Force facet_wrap to fill bottom row...但我无法让它在我的情况下运行。

1 个答案:

答案 0 :(得分:11)

facet_wrap只需将一个地图放在另一个地图后插入&#34;换行符&#34;在适当数量的情节之后。但是还有facet_grid允许您指定行索引和列索引。您的行索引是group,我现在添加一个列索引,如下所示:

cols<-c(a=1,c=1,f=1,b=2,d=2,g=2,e=3)
df$col <- as.factor(cols[as.character(df$name)])

现在您可以使用

绘制构面网格
ggplot(df, aes(x,y)) + geom_point() + facet_grid(group~col)

当然,根据您的问题,您必须考虑设置列索引的适当方法。

这是情节:

enter image description here

修改

为了回应您的评论并从this answer绘图,我创建了第二个解决方案。它使用gridExtra并直接操作ggplot grob。我认为它给出了期望的结果,但在我提出的形式中,它是&#34;手工作品&#34;。此解决方案使用facet_wrap代替facet_grid

首先,我添加一个&#34;占位符级别&#34;到变量name,这将确保创建空面,然后创建绘图:

df$name2 <- factor(df$name,levels=c('a','b','','c','d','e','f','g',' '))
p <- ggplot(df, aes(x,y)) + geom_point() + facet_wrap(~name2,ncol=3,drop=FALSE)

drop=FALSE是导致ggplot绘制空面的原因。 这个图与我的第一个解决方案的不同之处仅在于如何标注小平面。现在到了棘手的部分:

library(gridExtra)
g <- ggplotGrob(p)
## remove empty panels
g$grobs[names(g$grobs) %in% c("panel3", "panel9", "strip_t3", "strip_t9")] <- NULL
## remove them from the layout
g$layout <- g$layout[!(g$layout$name %in% c("panel-3", "panel-9", 
                                           "strip_t-3", "strip_t-9")),]
## move axis closer to panel
g$layout[g$layout$name == "axis_b-9", c("t", "b")] = c(9,9)

这基本上就是评论所说的。如果您使用另一组图表,请查看names(g$grobs)g$layout$name的输出,以确定哪些元素必须删除。

现在您可以使用

创建绘图
grid.newpage()
grid.draw(g)

enter image description here

编辑2:

对于较新版本的ggplot2,上述解决方案无效。不幸的是,我不知道这个版本是从哪个版本开始的,但它肯定不适用于2.2.1版本。

必须更改的部分是修改grob:

g <- ggplotGrob(p)
# get the grobs that must be removed
rm_grobs <- g$layout$name %in% c("panel-1-3", "panel-3-3", "strip-t-3-1", "strip-t-3-3")
# remove grobs
g$grobs[rm_grobs] <- NULL
g$layout <- g$layout[!rm_grobs, ]
## move axis closer to panel
g$layout[g$layout$name == "axis-b-3-3", c("t", "b")] = c(14.5, 14.5)
grid.newpage()
grid.draw(g)

主要变化是g$grobs不再是命名列表,并且grobs的名称已更改。请注意,面板标记为"panel-row-col",而灰色条标记为"strip-t-col-row"

enter image description here