2016-11-11 100 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