我有一个关于两个县人口的数据集:
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()
那不是我想要的。谢谢你的帮助!
答案 0 :(得分:1)
您可以将数据重新整形为宽屏格式,然后使用geom_ribbon()
填充County1
和County2
行之间的区域:
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"))