0

I am attempting to produce a stacked area graph using ggplot. Here is some code;

DATA <- data.frame("Band" = rep(c(1:10), each = 10), "Object" = rep(c("Tree", 
"Car", "Table", "Moon", "Tiger")), "Number" = runif(100, 1, 100), "Colour" = 
rep(c("Green", "Not Green"), each = 5))

ggplot(DATA, aes(x = Band, y = Number)) +
geom_area(aes(colour = Colour, fill = Colour), position = 'fill')

I end up with a bizarre "sawtooth" pattern, not two solid polygons. It doesn't matter if Band is an integer or numeric. If I treat Band as a factor, then I can get stacked lines, but with large gaps between them.

There are some similar questions here on SO; Making a stacked area plot using ggplot2 or stacked area graph in ggplot2 returned as stacked lines but the answers suggested there don't seem to resolve my problem. I think I'm making a silly mistake, but I can't work out what it is. Any suggestions are much appreciated. Thanks!

EcologyTom
  • 2,344
  • 2
  • 27
  • 38

1 Answers1

0

I was making a silly mistake. The Numbers needed to be summarised to total counts within Colour, not left as individual values for each Object.

library(dplyr)
DATA <- DATA %>% group_by(Colour, Band) %>% summarise_at(.vars = "Number", funs(sum))

And then the ggplot code above works fine.

EcologyTom
  • 2,344
  • 2
  • 27
  • 38