简体   繁体   English

ggplot堆积条形图

[英]ggplot Stacked bar chart

I would like to create a stacked chart using ggplot2 and geom_bar. 我想使用ggplot2和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). 我想要一个堆积图,其中x轴是Year,y轴是D1,D2,D3(D1,D2,D3颜色不同)的比例。

This is what I am thinking 这就是我的想法

Plot Chart 绘图图

ggplot(data = data1, mapping = aes(x = as.numeric(format(data1$Date, '%Y')), fill=D1)) 
+ geom_bar()

However, this will only plot D1. 但是,这只会绘制D1。 I am not sure what I need to do to add in the D2 and D3 on the same plot. 我不确定要在同一图中添加D2和D3,我需要做什么。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM