Reputation: 407
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.
Upvotes: 1
Views: 3223
Reputation: 60060
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")
Upvotes: 2
Reputation: 3026
Like this:
ggplot(df, aes(x=years, y = amount, fill =types))+
geom_bar(position = "stack", stat = "identity")
Upvotes: 2