Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove unused X axis levels in ggplot2 [duplicate]

Tags:

r

ggplot2

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

like image 721
Immanuel Williams Avatar asked May 25 '26 19:05

Immanuel Williams


1 Answers

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)

like image 85
Calum You Avatar answered May 27 '26 09:05

Calum You



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!