【问题标题】:How to make a stacked bar chart in ggplot2? [duplicate]如何在ggplot2中制作堆积条形图? [复制]
【发布时间】:2020-01-08 15:17:40
【问题描述】:

我是 R 语言的新手,我有一些格式如下的数据: 我想得到一个这样的堆积条的ggplot: 但我不知道怎么做。我尝试了很多东西,但没有任何效果。我想将“总受害者”作为最大的栏,并将另一个堆叠的栏放在受伤/死亡人数上。

【问题讨论】:

  • 您能否提供一个可重现的数据示例,而不是添加您的数据图像? stackoverflow.com/questions/5963269/…
  • 除了一个可重现的例子,你能更清楚地解释你想要什么吗?我的猜测是每年一个条形图,总的条形图是受害者总数,按受伤和死亡人数叠加,但在您的数据中,受伤和死亡人数比受害者总数还要多。
  • 这能回答你的问题吗? Plotting a stacked bar plot?

标签: r ggplot2


【解决方案1】:

您需要以更长的格式重塑数据,以便使用ggplot2 绘制它们。您可以使用tidyr 包的pivot_longer 函数来实现这一点:

library(tidyr)
library(dplyr)
library(ggplot2)

df %>% pivot_longer(.,-year, names_to = "Variable", values_to = "Value") %>%
  ggplot(aes(x = year, y = Value, fill = Variable))+
  geom_bar(stat = "identity", position = "fill")+
  scale_x_continuous(breaks = 2005:2017)+
  ylab("Victims")

如果要指定堆栈的特定顺序,可以更改因子变量的级别顺序:

library(tidyr)
library(dplyr)
library(ggplot2)

df %>% pivot_longer(.,-year, names_to = "Variable", values_to = "Value") %>%
  mutate(Variable = factor(Variable, levels = c("injured", "total", "fatal")))%>%
  ggplot(aes(x = year, y = Value, fill = Variable))+
  geom_bar(stat = "identity", position = "fill")+
  scale_x_continuous(breaks = 2005:2017)+
  ylab("Victims")

它回答了你的问题吗?

数据

structure(list(year = 2017:2005, fatal = c(113, 173, 210, 41, 
76, 99, 29, 9, 57, 28, 65, 24, 21), injured = c(558, 258, 179, 
60, 32, 111, 37, 5, 46, 30, 61, 16, 13), total = c(670, 418, 
360, 93, 101, 204, 65, 17, 100, 57, 123, 38, 31)), class = "data.frame", row.names = c(NA, 
-13L))

【讨论】:

  • geom_bar(stat = "identity", position = "fill") 可能更接近 OP 目标。
  • @JonSpring,你完全正确!我正在编辑我的答案。
  • 很高兴能为您提供帮助 ;)
猜你喜欢
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 2021-03-24
  • 2020-09-28
  • 1970-01-01
  • 1970-01-01
  • 2019-01-14
  • 1970-01-01
相关资源
最近更新 更多