首页 文章

在ggplot2中堆积的条形图

提问于
浏览
0

我在编写生成堆积条形图的代码时遇到问题,其中条形图的“总”值是数据框中值的总和 . 例如,我的数据格式如下:

amount    types years
7753547  Funding  2015
7370817  Funding  2016
4140110 Expenses  2015
4209865 Expenses  2016

我真的想要一个堆积的条形图,其中x轴是年份,填充是按类型,“总计”是资金金额,条形图按费用划分 . 因此,例如,在2015年,该栏上升至770万,然后被分配为414万 . 任何建议都会很棒 . 我一直试图找到一些代码但无济于事 . 谢谢 .

2 回答

  • 1

    由于您希望保持值不变,因此可以使用 position = "identity" . 如果有时费用高于资金,这可能无效,但对于您当前的示例可能是最简单的解决方案:

    ggplot(df, aes(x=factor(years), y = amount, fill = types)) +
        scale_y_continuous(labels = scales::comma) +
        geom_bar(position = "identity", stat = "identity")
    

    为了确保这反映了正确的数据,请参阅此修改,将 Expenses 完全置于较大的 Funding 栏中:

    ggplot(df, aes(x=factor(years), y = amount, fill = types))+
        scale_y_continuous(labels = scales::comma) +
        geom_bar(data = df[df$types == "Funding", ], position = "identity", stat = "identity",
                 width = 0.9, colour = "black") +
        geom_bar(data = df[df$types == "Expenses", ], position = "identity", stat = "identity",
                 width = 0.8, colour = "black")
    
  • 2

    像这样:

    ggplot(df, aes(x=years, y = amount, fill =types))+
      geom_bar(position = "stack", stat = "identity")
    

    enter image description here

相关问题