Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何放置';geom#u text';基于每个条的百分比?_R_Ggplot2_Geom Text - Fatal编程技术网

R 如何放置';geom#u text';基于每个条的百分比?

R 如何放置';geom#u text';基于每个条的百分比?,r,ggplot2,geom-text,R,Ggplot2,Geom Text,例如,我有一个数据框,如下所示,其中列为性别、年份、计数 gender year count Man 2020 220 Man 2019 206 Man 2018 216 Man 2017 156 Woman 2020 45 Woman 2019 47 然后我想把“%”放在每个堆叠的条上,每个条总共100%。我试过了,但我能得到的是基于总条数的百分比 例如,在2020年,我希望“男人”和(22

例如,我有一个数据框,如下所示,其中列为性别、年份、计数

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") 

我能做什么?

您可以计算每年的百分比,然后使用
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")