Search code examples
rggplot2bar-chartgeom-bar

geom_bar: stack without adding


I want a bar chart that looks stacked, but that the values are the actual values rather than being additive. I'm graphing things at ages, and ages don't "add".

The data below show that the oldest animal lives to be 31 days old. However, the graph indicates a value in the 60s because it is adding the days together.

x <- data.frame(species = c("Alpha", "Alpha", "Alpha","Beta", "Beta", "Beta","Gamma", "Gamma", "Gamma"), lifestage = factor(c("infant", "juvenile", "adult", "infant", "juvenile", "adult", "infant", "juvenile", "adult"),levels = c("infant", "juvenile", "adult")), age = c(10, 20, 30, 11, 21, 31, 9, 19, 29))

ggplot(x, aes(x = reorder(species, -age), y = age, fill = lifestage)) + 
       geom_bar(stat = "identity", position = position_stack(reverse = TRUE)) + 
       coord_flip()

How can I show the actual ages at which these events happen?


Solution

  • Figured it out - it's not a stacked graph I want, but a dodged graph with full overlap / no offset. position_dodge to the rescue!

    ggplot(x, aes(x = reorder(species, -age), y = age, fill = lifestage)) + 
              geom_bar(stat="identity", position = position_dodge(width = 0), width = 2)   + 
              coord_flip()