user3281413 user3281413 - 28 days ago 9
R Question

How do I add shaded regions to a line chart with multiple lines using ggplot?

I have a dataset on two county's population over time:

dat <- data.frame(Year=rep(c(2012, 2013, 2014, 2015), each=2),
Region=rep(c("County1", "County2"), 4),
Count=c(125082, 122335, 126474, 121661, 128220, 121627, 130269, 121802))


I'm able to do a line chart just fine:

ggplot(data=dat, aes(x=Year, y=Count, group=Region, fill = Region)) +
geom_line()


enter image description here

However, I want to be super cool and fill in the regions below the lines with color. When I try to use geom_area(), it seems to stack county2 over county1:

ggplot(dat, aes(x=Year, y=Count, fill = Region)) + geom_area()


enter image description here

That's not what I want. Thank you for your help!

Answer

You can reshape your data to wide format and then use geom_ribbon() to fill the area between County1 and County2 lines:

library(ggplot2); library(reshape2)
ggplot(dcast(Year ~ Region, data = dat), aes(x = Year)) + 
  geom_ribbon(aes(ymin = County1, ymax = County2, fill = "band")) + 
  scale_fill_manual("", values = "#AA44CC") + ylab('count')

enter image description here

To fill multiple ribbons, simply add another layer of ribbon, to visualize the result better, we start from 121000 here:

ggplot(dcast(Year ~ Region, data = dat), aes(x = Year)) + 
  geom_ribbon(aes(ymin = County1, ymax = County2, fill = "red"))  + ylab('Count') + 
  geom_ribbon(aes(ymin = 121000, ymax = County2, fill = "green"))

enter image description here