簡體   English   中英

如何在 R 中創建堆積條形圖,其中 y 軸應表示條形的百分比?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM