Geom_histogram: add bins with zero count?


Suppose I have a multiple choice question with five possible responses: A, B, C, D, E, and let’s say no one picks A or E. How can I nevertheless force these on the x-axis, albeit at zero?

here are three things I’ve tried:

# generate data
response <- tibble::tibble(answer = sample(LETTERS[2:4], 20, replace = T))

p <- ggplot(response) + geom_histogram(aes(x = answer), stat = "count", breaks = LETTERS[1:5])
p # this doesn't work; still only B,C,D shown

# Turning into a factor doesn't help
response %>% 
    mutate(answer = factor(answer, levels = LETTERS[1:5])) %>% 
    ggplot() + geom_histogram(aes(x = answer), stat = "count", bins = LETTERS[1:5])

# another attempt w scale_x_discrete; nope
p + scale_x_discrete(breaks = c("A", "B", "C", "D"))

Any advice from the hive is much appreciated-


If you change it to a factor and then use geom_bar with drop=FALSE in your sclae_x_discrete call you can get the desired result:

response %>%
  mutate(answer = factor(answer, LETTERS[1:5])) %>% 
  ggplot(aes(x = answer)) +
  geom_bar(stat = "count")+
  scale_x_discrete(drop = FALSE)

That gives you this: