I would like to create a stacked chart using ggplot2 and geom_bar.
This is my data:
Date D1 D2 D3
2017-05-08 .3 .5 .2
2017-02-22 .4 .4 .2
2016-11-23 .1 .5 .4
2016-05-13 .2 .6 .2
I want a stacked chart where the x-axis is the Year, the y-axis is the proportion of D1, D2, D3 (with D1, D2, D3 in different color).
This is what I am thinking
ggplot(data = data1, mapping = aes(x = as.numeric(format(data1$Date, '%Y')), fill=D1))
+ geom_bar()
However, this will only plot D1. I am not sure what I need to do to add in the D2 and D3 on the same plot.
Manually changing the data, I can create something like this. But I would like to do this in a more efficient way.
Try this:
require(ggplot2)
df$Date <- substr(df$Date,1,4)
plotDf <- melt(df, id.vars='Date')
plotDf <- aggregate(value ~ variable + Date,
mean, na.rm=TRUE, data=plotDf)
Output:
Sample data:
require(data.table)
df <- fread("Date D1 D2 D3
2017-05-08 .3 .5 .2
2017-02-22 .4 .4 .2
2016-11-23 .1 .5 .4
2016-05-13 .2 .6 .2")