如何使用ggplot将阴影区域添加到包含多行的折线图?

时间:2016-11-11 18:28:32

标签: r ggplot2 linechart

我有一个关于两个县人口的数据集:

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

enter image description here

然而,我想要超级酷,并用颜色填充线条下方的区域。当我尝试使用geom_area()时,似乎将county2叠加在county1上:

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

enter image description here

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

1 个答案:

答案 0 :(得分:1)

您可以将数据重新整形为宽屏格式,然后使用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')

enter image description here

要填充多个色带,只需添加另一个色带层,以更好地显示结果,我们从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"))

enter image description here