首页 > 解决方案 > ggplot - 比例堆积面积图

问题描述

我不明白为什么我的比例堆积面积图不工作。当我使用以下代码时,我会看到这种奇怪的倾斜视觉效果:

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")`

比例堆积面积图失败

但是当我将 geom_area 更改为 geom_bar 并添加 stat="identity" 时,条形图似乎工作得很好,即使它很难阅读(这就是我想要比例面积图的原因):

堆积条形图

链接到完整的数据集: https ://docs.google.com/spreadsheets/d/1Be4rhySLUGUXkNke8zirwxVpKCZw3uSmW4Hkku0Uc9E/edit?usp=sharing

任何帮助表示赞赏 - 非常感谢你。

标签: rggplot2

解决方案


您只需要准备数据,按 Year 和 Crime_type 分组。我使用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() 

在此处输入图像描述


推荐阅读