Home > database >  ggplot2: enforcing empty space for some missing levels in a plot
ggplot2: enforcing empty space for some missing levels in a plot

Time:06-16

In the following example (using the iris dataset), I am creating a factor class variable in which one of the species does not contain values of level C. When I make the plot, I cannot find a way to make ggplot not drop the empty level (virginica-C). In a enter image description here

PS: There is also another enter image description here See the definition of position_dodge2(): https://ggplot2.tidyverse.org/reference/position_dodge.html

CodePudding user response:

You could get the empty slot by faceting with scales = "free_x" and using scale_x_discrete(drop = FALSE):

(The strip labels could be moved to the bottom, and the fct_x labels & gaps between facets removed, if preferred per the second example.)

require(dplyr)
require(ggplot2)

iris %>%
  mutate(fct_x = factor(
    x = sample(x = c("A", "B", "C"), size = nrow(.), replace = TRUE),
    levels = c("A", "B", "C")
  )) %>%
  filter(!(Species == "virginica" & fct_x == "C")) %>%
  ggplot(aes(x = fct_x, y = Sepal.Length, fill = fct_x))  
  geom_boxplot()  
  facet_wrap(~ Species, scales = "free_x")  
  scale_x_discrete(drop = FALSE)

Created on 2022-06-16 by the reprex package (v2.0.1)

# Mimicing the original plot
require(dplyr)
require(ggplot2)

iris %>%
  mutate(fct_x = factor(
    x = sample(x = c("A", "B", "C"), size = nrow(.), replace = TRUE),
    levels = c("A", "B", "C")
  )) %>%
  filter(!(Species == "virginica" & fct_x == "C")) %>%
  ggplot(aes(x = fct_x, y = Sepal.Length, fill = fct_x))  
  geom_boxplot()  
  facet_wrap(~ Species, scales = "free_x", strip.position = "bottom")  
  scale_x_discrete(drop = FALSE)  
  theme(axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        strip.background = element_blank(),
        panel.spacing = unit(0, "lines"))  
  labs(x = "Species")

Created on 2022-06-16 by the reprex package (v2.0.1)

  • Related