首页 文章

ggplot堆积条形图

提问于
浏览
0

我想使用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

我想要一个堆积图表,其中x轴是年,y轴是D1,D2,D3的比例(D1,D2,D3为不同颜色) .

这就是我的想法

地块图

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

但是,这只会绘制D1 . 我不知道我需要做什么来在同一个地块上添加D2和D3 .

手动更改数据,我可以创建这样的东西 . 但我想以更有效的方式做到这一点 .
enter image description here

1 回答

  • 0

    试试这个:

    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)
    

    输出:

    enter image description here

    样本数据:

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

相关问题