如何在每个轴上带有因子变量的堆叠 ggplot Geom_bar 中显示每个级别的百分比?

问题描述 投票:0回答:1

我正在尝试创建一个水平堆叠条形图,其中显示每个级别的百分比。当我只有一个条形图时我可以做到这一点,但是当我也有一个fact9r变量作为x轴时,百分比将显示为总数的百分比而不是每个级别的百分比(即每个条形图上的百分比应添加到100 而不是整个图表中的百分比)。

这是我的一个例子

 data <- data.frame( Variable1 = factor(c( 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'd', 'e' ), levels = c('a', 'b', 'c', 'd', 'e') ), Variable2 = factor( c( "Yes", "Yes", "Yes", "No", "Yes", "Yes", "No", "Yes", "No", "Yes"), levels = c("Yes", "No")))

我现在绘制它的代码如下所示:

`ggplot(data, aes(x = Variable2, fill = Variable1)) +
  geom_bar(position = "fill") +
  coord_flip() +
  theme_classic() +
  geom_text(
       aes(label = paste0(round(after_stat(count / sum(count)) * 100), "%")),
       stat = "count",
       size = 3,
       hjust = 0.7,
       position = position_fill(vjust = 0.5),
     )   `

我尝试用这个来制作百分比:

`percentages <- data %>%
  group_by(Variable1, Variable2) %>%
  summarise(Count = n()) %>%
  group_by(Variable1) %>%
  mutate(Percentage = (Count / sum(Count)) * 100)`

并将它们显示为 geom_text 但我无法让它工作。有人可以帮忙吗?我已经尝试了这里的所有答案,但无法让它们使用我的数据。

r ggplot2 geom-bar geom-text
1个回答
0
投票

这是解决您的问题的一种方法:

library(dplyr, warn = FALSE)
library(ggplot2)

percentages <- data %>%
  count(Variable2, Variable1, name = "Count") %>%
  group_by(Variable2) %>%
  mutate(Percentage = Count / sum(Count))

ggplot(data, aes(y = Variable2, fill = Variable1)) +
  geom_bar(position = "fill") +
  theme_classic() +
  geom_text(
    data = percentages,
    aes(x = Count, label = scales::percent(Percentage)),
    size = 3,
    position = position_fill(vjust = 0.5)
  )

© www.soinside.com 2019 - 2024. All rights reserved.