Search code examples
rggplot2

Leaving a space in geom_bar with stat='bin', position='dodge' and zeroes


Let's say I am plotting some data like this:

x = data.frame(cat=c('a', 'a', 'a', 'b', 'b'), type=c('x', 'x', 'y', 'x', 'x'))
ggplot(x, aes(cat, fill=type)) + geom_bar(stat='bin', position='dodge')

Which gives me a plot like this:

enter image description here

However, what I want is for the bars to all be the same width, such that there is an empty space for cat=='b' where the blue bar would be. How do I do this?


Solution

  • This may be a potential solution, although I would be happy to hear if there is something better.

    ggplot(as.data.frame(table(x$cat, x$type)), aes(Var1, Freq, fill=Var2)) + geom_bar(stat='identity', position='dodge')