如何在ggplot2中制作堆积的条形图?

时间:2020-01-08 15:17:40

标签: r ggplot2

我是R语言的新手,我有一些数据的格式如下: enter image description here 我想得到一个带有堆叠条形图的ggplot: enter image description here 但是我不知道该怎么做。我尝试了很多事情,但没有任何效果。我想作为“最大受害者”作为最大的障碍,而将其他受伤/致命的栅栏放置在上面。

1 个答案:

答案 0 :(得分:0)

您需要以更长的格式来重塑数据,以便使用ggplot2进行绘制。您可以使用pivot_longer软件包的tidyr函数来实现此目的:

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

enter image description here

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

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

enter image description here

它回答了您的问题吗?

数据

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