Stacked area chart are often use to represent time series. These examples are inspired from the cookbook for R. Check the dataviz catalog to better understand what is a stacked area graph! Let’s build some data for the next examples:
1 2 3 4 5 6 7 8 9 |
# ggplot2 library library(ggplot2) # DATA set.seed(345) Sector <- rep(c("S01","S02","S03","S04","S05","S06","S07"),times=7) Year <- as.numeric(rep(c("1950","1960","1970","1980","1990","2000","2010"),each=7)) Value <- runif(49, 10, 100) data <- data.frame(Sector,Year,Value) |
This is the basic stacked area plot proposed by ggplot2.
1 2 |
ggplot(data, aes(x=Year, y=Value, fill=Sector)) + geom_area() |
You can easily change the color palette:
1 2 3 |
ggplot(data, aes(x=Year, y=Value, fill=Sector)) + geom_area(colour="black", size=.2, alpha=.4) + scale_fill_brewer(palette="Greens", breaks=rev(levels(data$Sector))) |
To reverse the stacking order, you have to change the order in the initial data frame
1 2 3 4 |
data=data[order(data$Sector, decreasing=T) , ] ggplot(data, aes(x=Year, y=Value, fill=Sector)) + geom_area(colour="black", size=.2, alpha=.4) + scale_fill_brewer(palette="Greens", breaks=rev(levels(data$Sector))) |
Thus you can give a specific order, still reordering the dataframe as needed:
1 2 3 |
data$Sector=factor(data$Sector , levels=levels(data$Sector)[c(1,4,3,2,7,6,5)]) ggplot(data, aes(x=Year, y=Value, fill=Sector)) + geom_area() |
You can also draw a proportional stacked area graph: the sum of each year is always equal to hundred and value of each group is represented through percentages. To make it, you have to calculate these percentages first:
1 2 3 4 5 |
my_fun=function(vec){ as.numeric(vec[3]) / sum(data$Value[data$Year==vec[2]]) *100 } data$prop=apply(data , 1 , my_fun) ggplot(data, aes(x=Year, y=prop, fill=Sector)) + geom_area(alpha=0.6 , size=1, colour="black") |
Not what you are looking for ? Make a new search ![mediatagger]
need a commonds to draw a time series with double y axis (left and right both) from excel sheet