如何使用 ggplot 将阴影区域添加到具有多条线的折线图中?

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

我有一个关于两个县随时间变化的人口的数据集:

 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))

我可以很好地制作折线图:

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

但是,我想超级酷,用颜色填充线条下方的区域。当我尝试使用 geom_area() 时,它似乎将 county2 堆叠在 county1 之上:

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

那不是我想要的。感谢您的帮助!

您可以将数据重新整形为宽格式,然后使用 geom_ribbon() 填充 County1County2 行之间的区域:

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')

要填充多个丝带,只需添加另一层丝带,为了更好地可视化结果,我们从 121000 开始:

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"))