Sean
Sean

Reputation: 51

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?

Upvotes: 0

Views: 1562

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

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

Upvotes: 1

Related Questions