[英]How do I create a frequency stacked bar chart however have percentage labels on the bars and frequencies on the y axis, in R?
[英]How do I create a stacked bar chart in R, where the y axis should denote the percentages for the bars?
我想在 R 中创建一个堆积条形图。我的 X 轴只包含性别数据,即男性或女性。 我只需要 y 轴来显示堆叠条的百分比。 “Survived”列只是 0 和 1 的混合。 即 1 表示个人在经历中幸存下来,而 0 表示个人没有在经历中幸存下来。 我不确定要为 y 标签添加什么。 有人可以帮忙吗?
ggplot(data = df, mapping = aes(x = Sex, y = ? , fill = Survived)) + geom_bar(stat = "identity")
一种可能的解决方案是使用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
现在是绘图部分:
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()
可重现的例子
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.