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


i have dataset on 2 county's population on time:

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

i'm able line chart fine:

ggplot(data=dat, aes(x=year, y=count, group=region, fill = region)) + geom_line() 

enter image description here

however, want super cool , fill in regions below lines color. when try use geom_area(), seems stack county2 on county1:

ggplot(dat, aes(x=year, y=count, fill = region)) + geom_area() 

enter image description here

that's not want. thank help!

you can reshape data wide format , use geom_ribbon() fill area between county1 , county2 lines:

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

to fill multiple ribbons, add layer of ribbon, visualize result better, start 121000 here:

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


Comments

Popular posts from this blog

php - trouble displaying mysqli database results in correct order -

depending on nth recurrence of job in control M -

sql server - Cannot query correctly (MSSQL - PHP - JSON) -