Plot zero-count factor levels on bar chart -- ggplot2

Hi, I am creating a bar chart of a factor variable. One of the levels has no counts in the data, but I would still like to have it included on the x-axis of my chart. How could I do this? I learned earlier on this forum how to do the equivalent to a table but couldn't figure how to translate to a chart.

Thanks in advance.

library(ggplot2)

# 3 factor variable 
y <- data.frame(howgood = c("Better","Better","Good","Good","Better"))
y$howgood <- factor(y$howgood, levels = c("Good", "Better", "Best"))

# How to include factor "Best" on the x axis (with a 0 count)? 
ggplot(y, aes(howgood)) + geom_bar()
1 Like

You just have to add scale_x_discrete(drop=FALSE)

library(ggplot2)

y <- data.frame(howgood = c("Better","Better","Good","Good","Better"))
y$howgood <- factor(y$howgood, levels = c("Good", "Better", "Best"))

ggplot(y, aes(howgood)) +
    geom_bar() +
    scale_x_discrete(drop=FALSE)

Created on 2019-03-19 by the reprex package (v0.2.1)

5 Likes

Beautiful, thank you! Resolved.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.