Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

r - How to put 'geom_text' percent based on each bar?

For example, I have a data frame as below with columns gender, year, count.

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

Then I would like to put '%' on each stacked-bar with 100% per each bar in total. I tried but what I can get is separated % based on total bars.

enter image description here

For instance, on year 2020 I would like to have 'Man' with % of (220 / 220 + 45), and 'Woman' with (45 / 220 + 45).

This is the code I tired.

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

What can I do?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can calculate the percentage for each year and then plot it using 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")

enter image description here

Maybe changing Y-axis to percentage instead of count would be a better idea.


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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...