Julien Navarre
Julien Navarre

Reputation: 7830

Remove Factors with no data in facet grouping variable

I have the following data :

data <- data.frame(x = letters[1:6], 
                   group = rep(letters[1:2], each = 3), 
                   y = 1:6)

  x group y
1 a     a 1
2 b     a 2
3 c     a 3
4 d     b 4
5 e     b 5
6 f     b 6

And I would like to plot y ~ x and split into facets by groups with ggplot2.

ggplot(data, aes(x, y)) + 
  geom_bar(stat = "identity") + 
  facet_grid(group ~ .)

enter image description here

The problem is that some tuples (x; group) don't exist in my data(for example there is no data for x = a && group = b) , but they are kept in the x-axis of both facets so I would like to remove them and then remove white spaces in the facets when factors are missing in respective groups.

I thought scales = "free_x" or drop = TRUE could do the trick but I couldn't manage to do it.

Any help would be appreciated, Thanks !

Upvotes: 4

Views: 1701

Answers (1)

user7396508
user7396508

Reputation:

Use facet_wrap instead

ggplot(data, aes(x, y)) + 
     geom_col() + 
     facet_wrap(~group, scales = 'free', nrow = 2, strip.position = 'right')

also note geom_col as an alternative to using identity

Upvotes: 6

Related Questions