ggplot - Proportional stacked area plot

Multi tool use
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")`



Proportional Stacked Area Graph Fail



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):



Stacked Bar Plot



Link to full data-set:
https://docs.google.com/spreadsheets/d/1Be4rhySLUGUXkNke8zirwxVpKCZw3uSmW4Hkku0Uc9E/edit?usp=sharing



Any help is appreciated - thank you very much.





It's best if you provide your data using dput so that people can copy it directly.
– Lyngbakr
Jun 29 at 14:59


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()



enter image description here





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.

2HF Aq8rX
50Nb dl,u4bHXRAZaVj2j,tjP,jNG6rIFEv0v phrXzZGq3rZ,CzW,BJsHK ukJBm,YS2s 6Zvig W1D,azDfDDv3A66OmLAZvj

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

Create weekly swift ios local notifications