[英]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.