facet_wrap
只需将一个图放在另一个图之后,并在适当数量的图之后插入“换行符”即可。但也有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)
当然,根据您的问题是什么,您必须考虑设置列索引的适当方法。
这是情节:
Edit:
为了回应您的评论和绘图这个答案 https://stackoverflow.com/a/18338240/4303162,我创建了第二个解决方案。它用gridExtra
并直接操作 ggplot grob。我认为它给出了期望的结果,但以我呈现的形式,它是“手动工作”。该解决方案使用facet_wrap
代替facet_grid
.
首先,我向变量添加“占位符级别”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)
and g$layout$name
找出必须删除哪些元素。
现在您可以使用以下命令创建绘图
grid.newpage()
grid.draw(g)
Edit 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"
.