Deleting an entire row of facets of unused factor level combination

210 Views Asked by At

I want to remove the 2nd row of facets from my plot below because there is no data for that factor combination.

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) 

I tried to use the idea from 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)

..but got this.

How do I eliminate the white space? Also, is there a straightforward solution to this, without having to manipulate the grobs, etc?

1

There are 1 best solutions below

2
On BEST ANSWER

Just modify the data:

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