R语言 具有多个分类变量的水平百分比堆叠条形图

khbbv19g  于 2023-02-14  发布在  其他
关注(0)|答案(1)|浏览(159)

我需要一个百分比堆叠水平条形图,其中每个条形图是一个 Dataframe 的<fct>变量。
数据示例为:

A       B       C 
    <fct>   <fct>   <fct>
1   Sim     Não     Não 
2   Sim     Não     Sim 
3   Sim     Não     Sim 
4   NA      Sim     Sim 
5   Não     Não     Não

结果示例如下:

我做了大量的搜索,但还是不明白如何正确地转换数据以传递给ggplot。

0yg35tkg

0yg35tkg1#

你可以

library(tidyverse)

df %>%
  pivot_longer(everything()) %>%
  group_by(name) %>%
  mutate(group_size = n()) %>%
  group_by(name, value) %>%
  summarize(group_percent = n() / mean(group_size)) %>%
  ggplot(aes(y = name, x = group_percent, fill = value)) +
  geom_col(width = 0.6, position = position_fill()) +
  geom_text(aes(label = scales::percent(group_percent)),
            position = position_fill(vjust = 0.5)) +
  scale_fill_manual(values = c("#1f77b4", "#ff7f0e"), na.value = 'green4') +
  theme_classic(base_size = 16) +
  scale_x_continuous('Percent', labels = scales::percent, expand = c(0, 0)) +
  coord_fixed(0.1) +
  theme(panel.border = element_rect(fill = NA))

相关问题