2016-11-11 96 views
1

我有两个县的人口数据集随着时间的推移:如何使用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() 

enter image description here

不过,我想超级酷,并填充颜色线下方的区域。当我尝试使用geom_area(),它似乎在county1堆放county2:

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

enter image description here

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

+2

退房'geom_ribbon' – ddunn801

回答

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

+0

谢谢!你知道我怎样才能为郡2添加第二个功能区(即从剧情的底部到县2的值)? –

+0

您可以添加另一层功能区,使用'ymin'作为底线,'ymax'作为'县2'值,请参阅更新。 – Psidom