3

I would like to have the ggplot only display levels where there is data. So for the first facet S7, S8, S9 should not appear & for the second facet S1, S2, S3 should not appear. Please let me know if I articulated myself correctly.

df = data.frame(v1 = c('A','A','A','B','B','B'),
           v2 = c('S1','S2','S3','S7','S8','S9'),
           nm = c(2,3,4,5,6,7))



ggplot(df,aes(x =  v2, y = nm)) +
  geom_point(size = 3) +
  facet_grid(.~v1) 

enter image description here

phalteman
  • 3,442
  • 1
  • 29
  • 46
  • 1
    Does this answer your question? [ggplot: how to remove unused factor levels from a facet?](https://stackoverflow.com/questions/57026999/ggplot-how-to-remove-unused-factor-levels-from-a-facet) – phalteman Jan 17 '20 at 23:49

1 Answers1

7

Use scales = "free_x" to control whether the x-axis is forced to have the same limits on different facets:

library(ggplot2)
df <- data.frame(
  v1 = c("A", "A", "A", "B", "B", "B"),
  v2 = c("S1", "S2", "S3", "S7", "S8", "S9"),
  nm = c(2, 3, 4, 5, 6, 7)
)



ggplot(df, aes(x = v2, y = nm)) +
  geom_point(size = 3) +
  facet_grid(. ~ v1, scales = "free_x")

Created on 2020-01-17 by the reprex package (v0.3.0)

Calum You
  • 14,687
  • 4
  • 23
  • 42