s_baldur
s_baldur

Reputation: 33508

Show empty groups even when all groups are empty

Using scale_x_discrete(drop = FALSE) I manage to keep empty groups on its place on the x-axis:

library(ggplot2)
iris_filtered <- subset(iris, Sepal.Length > 7)
ggplot(data = iris_filtered, mapping = aes(x = Species, y = Sepal.Width)) +
  geom_boxplot() +
  scale_x_discrete(drop = FALSE)

enter image description here

Except when all the groups are empty, I get:

iris_filtered <- subset(iris, Sepal.Length > 8)
ggplot(data = iris_filtered, mapping = aes(x = Species, y = Sepal.Width)) +
  geom_boxplot() +
  scale_x_discrete(drop = FALSE)

enter image description here

My hoped-for-output is:

enter image description here

Upvotes: 2

Views: 299

Answers (1)

Ahorn
Ahorn

Reputation: 3876

You could just specify the x-axis limits:

iris_filtered <- subset(iris, Sepal.Length > 8)
ggplot(data = iris_filtered, mapping = aes(x = Species, y = Sepal.Width)) +
  geom_boxplot() +
  scale_x_discrete(drop = FALSE, limits = unique((iris$Species))

enter image description here

Similar approach to show the scale of the y-axis:

ggplot(data = iris_filtered, mapping = aes(x = Species, y = Sepal.Width)) +
  geom_boxplot() +
  scale_x_discrete(drop = FALSE, limits = c("a","b","c")) +
  ylim(min(iris$Sepal.Length), max(iris$Sepal.Length))

enter image description here

Upvotes: 5

Related Questions