0

I have the following sample data. The variable "y" has 4 factor levels. However, only 3 of them appear in the data.

How can I add the missing category "C" to the legend (and not necessarily to the plot)?

library(tidyverse)

# Sample data
n <- 100
df <- data.frame(x = sample(c("grp1","grp2", "grp3", "grp4"), size = n, replace = TRUE),
                 y = sample(c("A", "B", "D", "E"), size = n, replace = TRUE)) %>%
  mutate(x = as.factor(x),
         y = factor(y, levels = c("A", "B", "C", "D", "E")))

# Stacked barplot
df %>%
  group_by(x) %>%
  count(y) %>%
  mutate(percent = 1 / sum(n) * n) %>%
  
  ggplot(aes(x = x, y = percent, fill = y)) + geom_col()
zx8754
  • 52,746
  • 12
  • 114
  • 209
D. Studer
  • 1,711
  • 1
  • 16
  • 35
  • 1
    See this answer in linked post: https://stackoverflow.com/a/22831155/680068 We need `scale_fill_discrete(drop = FALSE)` – zx8754 Jan 05 '23 at 10:45

0 Answers0