[英]How do I create a stacked bar chart in R, where the y axis should denote the percentages for the bars?
I would like to create a stacked bar chart in R. My X axis just contains data on sex ie male or female.我想在 R 中创建一个堆积条形图。我的 X 轴只包含性别数据,即男性或女性。 I just need the y axis to show percentages of the stacked bars.
我只需要 y 轴来显示堆叠条的百分比。 The "Survived" column is just a mixture of 0s and 1s.
“Survived”列只是 0 和 1 的混合。 Ie 1 denoting that an indiividual survived an experience and 0 showing that the individual did not survive the experience.
即 1 表示个人在经历中幸存下来,而 0 表示个人没有在经历中幸存下来。 I am not sure what to put in for the y label.
我不确定要为 y 标签添加什么。 Can anyone help please?
有人可以帮忙吗?
ggplot(data = df, mapping = aes(x = Sex, y = ? , fill = Survived)) + geom_bar(stat = "identity") ggplot(data = df, mapping = aes(x = Sex, y = ? , fill = Survived)) + geom_bar(stat = "identity")
One possible solution is to use dplyr
package to calculate percentage of each categories outside of ggplot2
and then use those values to get your bargraph using geom_col
:一种可能的解决方案是使用
dplyr
包计算ggplot2
之外每个类别的ggplot2
,然后使用这些值使用geom_col
获取条形图:
library(dplyr)
df %>% count(Sex, Survive) %>%
group_by(Sex) %>%
mutate(Percent = n/sum(n)*100)
# A tibble: 4 x 4
# Groups: Sex [2]
Sex Survive n Percent
<fct> <dbl> <int> <dbl>
1 F 0 26 55.3
2 F 1 21 44.7
3 M 0 34 64.2
4 M 1 19 35.8
And now with the plotting part:现在是绘图部分:
library(dplyr)
library(ggplot2)
df %>% count(Sex, Survive) %>%
group_by(Sex) %>%
mutate(Percent = n/sum(n)*100) %>%
ggplot(aes(x = Sex, y = Percent, fill = as.factor(Survive)))+
geom_col()
Reproducible example可重现的例子
df <- data.frame(Sex = sample(c("M","F"),100, replace = TRUE),
Survive = sample(c(0,1), 100, replace = TRUE))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.