ggplot - Proportional stacked area plot

Multi tool use
ggplot - Proportional stacked area plot
I don't understand why I'm not getting my proportional stacked area graph to work. When I use the following code, I get this weird skewed visual:
ViolentCrimes <- ddply(ViolentCrimes, "Year", transform, PercentofTotal = Number_of_Crimes/sum(Number_of_Crimes) * 100)
ggplot(ViolentCrimes, (aes(x = Year, y = PercentofTotal, fill = Crime_Type)) +
geom_area() +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
ylab("Percent of Total")`
But when I change geom_area to geom_bar, and add stat="identity", the bar graph seems to work just fine, even though it's hard to read (which is why I wanted the proportional area graph):
Link to full data-set:
https://docs.google.com/spreadsheets/d/1Be4rhySLUGUXkNke8zirwxVpKCZw3uSmW4Hkku0Uc9E/edit?usp=sharing
Any help is appreciated - thank you very much.
dput
My bad, first-time question asker... dput was messy, so I included a link to the full data.
– Lantz McGinnis-Brown
Jun 29 at 15:09
1 Answer
1
You just need to prepare your data, grouping by Year and Crime_type. I use dplyr
:
dplyr
library(dplyr)
ViolentCrimes <- df %>%
group_by(Year, Crime_Type) %>%
summarise(n = sum(Number_of_Crimes)) %>%
mutate(percentage = n / sum(n))
ggplot(ViolentCrimes, (aes(x = Year, y = percentage, fill = Crime_Type))) +
geom_area()
Wow, I need to get better at piping. This is very helpful.
– Lantz McGinnis-Brown
Jul 2 at 19:46
@LantzMcGinnis-Brown Glad to help. Thank you.
– mpalanco
Jul 2 at 20:42
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
It's best if you provide your data using
dput
so that people can copy it directly.– Lyngbakr
Jun 29 at 14:59