我在编写生成堆积条形图的代码时遇到问题,其中"总计" bar的值是数据框中值的总和。例如,我的数据格式如下:
amount types years
7753547 Funding 2015
7370817 Funding 2016
4140110 Expenses 2015
4209865 Expenses 2016
我真的想要一个堆积的条形图,其中x轴是年份,填充是按类型,"总计"是资金金额,金额是按费用划分的。因此,例如,在2015年,该栏上升至770万,然后被分配为414万。任何建议都会很棒。我一直试图找到一些代码,但无济于事。谢谢。
答案 0 :(得分:2)
像这样:
ggplot(df, aes(x=years, y = amount, fill =types))+
geom_bar(position = "stack", stat = "identity")
答案 1 :(得分: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")