Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove empty facet with ggplot?

I am doing geom_point with ggplot using facet_grid, but i get facet empty and i do not know how to delete them or how to structure my data to not have empty facet ?

This is a example of my data :

data = data.frame(
  F1=c(0.69, 0.59, 0.6 , 0.52, 0.56, 0.58, 0.52, 0.53, 0.41, 0.57,
       0.54, 0.38, 0.48, 0.31, 0.35,
       0.43, 0.36, 0.38, 0.23, 0.48, 0.55, 0.48, 0.49, 0.46, 0.49,
       0.52, 0.48, 0.48, 0.35, 0.5 ,
       0.51, 0.58, 0.51, 0.59, 0.51, 0.57, 0.5 , 0.59, 0.47, 0.51,
       0.61, 0.58, 0.61, 0.59, 0.61, 0.67, 0.6 , 0.59, 0.47, 0.61,
       0.61, 0.52, 0.53, 0.60,0.62, 0.53, 0.62, 0.63, 0.24, 0.38),
  F2 = c(0.01, 0.01, 0.02, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01,
         0.42, 0.35, 0.43, 0.31, 0.34, 0.41, 0.34, 0.34, 0.42, 0.39, 0.44, 0.43,
         0.49, 0.43, 0.42, 0.53, 0.41, 0.42, 0.50, 0.40 ,
         0.53, 0.58, 0.57, 0.55, 0.51, 0.65, 0.51, 0.52, 0.62, 0.49,
         0.63, 0.68, 0.67, 0.66, 0.61, 0.66, 0.61, 0.62, 0.62, 0.49,
         0.84, 0.65, 0.69, 0.56, 0.72, 0.61, 0.73, 0.68, 0.72, 0.72),
  s1= c(rep(c("a"),10),
        rep(c("b"),10),
        rep(c("c"),10),
        rep(c("d"),10),
        rep(c("f"),10),
        rep(c("g"),10)),
  s2= c(rep(c("g1"),20),
        rep(c("g2"),40)),
  M=rep(c("M1",
          "M2",  
          "M3",    
          "M4",    
          "M5",   
          "M6",         
          "M7", 
          "M8",
          "M9",
          "M10"),6))

My code :

ggplot (data, aes (x = F1, y = F2, shape = M)) +
  facet_grid(s2 ~ s1) + scale_shape_manual(values=c(7,13,23,0,8,1,15,2,17,3,25))+
  geom_point () 

I get that :

enter image description here

Plot expected : enter image description here

like image 325
Ph.D.Student Avatar asked Feb 10 '26 13:02

Ph.D.Student


2 Answers

I don't know why facet_wrap wouldn't work

the code below produces what you want

p <- ggplot (data, aes (x = F1, y = F2, shape = M))
p <- p + geom_point () 
p <- p +  facet_wrap(s2 ~ s1,ncol=2) + scale_shape_manual(values=c(7,13,23,0,8,1,15,2,17,3,25))
p
like image 193
Boidot Avatar answered Feb 13 '26 12:02

Boidot


If you really need to create that example output with strip labels on both sides, you'll need to create three plots, something like:

p3 <- ggplot(subset(data, s1 %in% c('f', 'g')), aes(F1, F2, shape = M)) + 
  geom_point() + 
  facet_grid(s2 ~ s1) +
  scale_shape_manual(values = c(7,13,23,0,8,1,15,2,17,3,25))
p1 <- p3 %+% subset(data, s1 %in% c('a', 'b')) +
  theme(axis.text.x = element_blank(), axis.ticks.x = element_blank(), 
        axis.title.x = element_blank(), legend.position = 'none')
p2 <- p1 %+% subset(data, s1 %in% c('c', 'd'))

cowplot::plot_grid(p1, p2, p3, nrow = 3, align = 'v', axis = 'lr', rel_heights = c(1, 1, 1.2))

But I would generally go with the easier wrap solution by @Boidot.

like image 38
Axeman Avatar answered Feb 13 '26 13:02

Axeman