【问题标题】:How do I create a stacked bar chart in R, where the y axis should denote the percentages for the bars?如何在 R 中创建堆积条形图,其中 y 轴应表示条形的百分比?
【发布时间】:2020-03-05 17:07:36
【问题描述】:

我想在 R 中创建一个堆积条形图。我的 X 轴只包含性别数据,即男性或女性。我只需要 y 轴来显示堆叠条的百分比。 “Survived”列只是 0 和 1 的混合。即 1 表示个人在经历中幸存下来,0 表示个人没有在经历中幸存下来。我不确定为 y 标签添加什么。有人可以帮忙吗?

ggplot(data = df, mapping = aes(x = Sex, y = ? , fill = Survived)) + geom_bar(stat = "identity")

【问题讨论】:

标签: r stacked-chart


【解决方案1】:

一种可能的解决方案是使用dplyr 包计算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))

【讨论】:

    猜你喜欢
    • 2018-12-15
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 2017-08-29
    • 2017-03-18
    相关资源
    最近更新 更多