1
votes

I am having trouble writing a code that produces a stacked bar chart where the "total" value for the bar is the sum of the values in my data frame. For example, I have my data in the following format:

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

I really want a stacked bar chart where the x-axis is the year, fill is by types, and the "total" is the funding amount and the bar is partitioned by expenses. So, for example, in 2015, the bar goes up to 7.7 million and then is partitioned off at 4.14 million. Any suggestions would be great. I've been attempting to find some code but to no avail. Thank you.

2
I think your description of what you want is a bit contradictory. If the top of each bar is just the value of the Funding row for that year, then you don't really want the sum of the values, you want the values represented as they currently are without summing. Can you clarify?Marius
Hi, Marius. Sorry for the very poor description--I have the image in my head but am having trouble describing it. When I run my code right now, the bar's total is 7.7 million + 4.14 million. However, I need the peak of the bar to be 7.7 million and for the bar to be cut up at 4.14 million. Basically, I want to show how much was funded and how much of that funding was spent. Does this help a bit?user122514

2 Answers

2
votes

Since you want to keep the values as they are, you can use position = "identity". This may not work if sometimes expenses are greater than funding, but is probably the simplest solution for your current example:

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

To reassure yourself that this is reflecting the correct data, see this modification that puts Expenses fully inside the larger Funding bar:

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
votes

Like this:

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

enter image description here