删除未使用的因子级别组合的整行方面

时间:2016-12-20 07:39:47

标签: r ggplot2 grid facet

我想从下面的图中删除第二行方面,因为没有该因子组合的数据。

library(ggplot2)
library(grid)
set.seed(5000)

# generate first df
df1 = data.frame(x=rep(rep(seq(2,8,2),4),6), 
                 y=rep(rep(seq(2,8,2),each=4),6),
                 v1=c(rep("x1",32),rep("x2",64)),
                 v2=c(rep("y1",64),rep("y2",32)),
                 v3=rep(rep(c("t1","t2"),each=16),3),
                 v4=rbinom(96,1,0.5)) 

# generate second df
df2 = data.frame(x=runif(20)*10, y=runif(20)*10,
                 v1=sample(c("x1","x2"),20,T))

# plot
ggplot() + 
  geom_point(data=df1, aes(x=x, y=y, colour = factor(v4)), shape=15,  size=5) + 
  scale_colour_manual(values = c(NA,"black")) + facet_grid(v1+v2~v3, drop = T) +
  geom_point(data=df2, aes(x=x,y=y), shape=23 , colour="black", fill="white", size=4) + 
  coord_equal(ratio=1) + xlim(0, 10) + ylim(0, 10) 

我尝试使用this post ..

中的想法
g=ggplotGrob(y)
pos=which(g$layout$t==5 | g$layout$t==6)
g$layout=g$layout[-c(pos),]
g$grobs=g$grobs[-c(pos)]
grid.newpage()
grid.draw(g)

..但是得到了这个。

如何消除空白区域?此外,是否有一个简单的解决方案,而不必操纵凹凸等?

1 个答案:

答案 0 :(得分:2)

只需修改数据:

df2 <- rbind(cbind(df2, v2 = "y1"),
             cbind(df2, v2 = "y2"))
df2 <- df2[!(df2$v1 == "x1" & df2$v2 == "y2"),]

# plot
ggplot() + 
  geom_point(data=df1, aes(x=x, y=y, colour = factor(v4)), shape=15,  size=5) + 
  scale_colour_manual(values = c(NA,"black")) + facet_grid(v1+v2~v3, drop = T) +
  geom_point(data=df2, aes(x=x,y=y), shape=23 , colour="black", fill="white", size=4) + 
  coord_equal(ratio=1) + xlim(0, 10) + ylim(0, 10) 

resulting plot