【问题标题】:How to put 'geom_text' percent based on each bar?如何根据每个条放置“geom_text”百分比?
【发布时间】:2021-01-01 03:05:14
【问题描述】:

例如,我有一个如下的数据框,其中包含性别、年份、计数列。

gender year count  
Man    2020 220     
Man    2019 206     
Man    2018 216     
Man    2017 156             
Woman  2020 45      
Woman  2019 47

然后我想在每个堆叠条上放置 '%' ,每个条总共 100%。我试过了,但我能得到的是基于总条数的分离百分比。

例如,在 2020 年,我希望“男人”的百分比为 (220 / 220 + 45),而“女人”的百分比为 (45 / 220 + 45)。

这是我厌倦的代码。

ggplot(data = all_gen, aes(x = year, y = count, fill = gender)) +
  geom_col() +
  geom_text(aes(label = paste0(round(count / sum(count) * 100, 1), "%")), position = position_stack(vjust = 0.5), vjust = 0.5, hjust = 0.3, size = 4.5, col = "black") +
  labs(x = "", y = "Count", title = "Gender by year") 

我能做什么?

【问题讨论】:

    标签: r ggplot2 geom-text


    【解决方案1】:

    您可以计算每年的百分比,然后使用ggplot2 绘制它:

    library(dplyr)
    library(ggplot2)
    
    all_gen %>%
      group_by(year) %>%
      mutate(percentage = paste(round(prop.table(count) * 100, 2), '%')) %>%
      ggplot(aes(x = year, y = count, fill = gender, label = percentage)) + 
      geom_col() + 
      geom_text(position = position_stack(vjust = 0.5), 
                hjust = 0.5, size = 4.5, col = "black") + 
      labs(x = "", y = "Count", title = "Gender by year")
    

    也许将 Y 轴改为百分比而不是计数会更好。

    
    all_gen %>%
      group_by(year) %>%
      mutate(percentage = round(prop.table(count) * 100, 2)) %>%
      ggplot(aes(x = year, y = percentage, fill = gender, 
                 label = paste0(percentage, '%'))) + 
      geom_col() + 
      geom_text(position = position_stack(vjust = 0.5), 
                hjust = 0.5, size = 4.5, col = "black") + 
      labs(x = "", y = "Percentage", title = "Gender by year")
    

    【讨论】:

      猜你喜欢
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 2021-01-30
      相关资源
      最近更新 更多