Home > Back-end >  ggplot2 add total number count to legend
ggplot2 add total number count to legend

Time:03-26

i have a graph with the code

all_trips2 %>% 
count(member_casual) %>% mutate(pct = prop.table(n), total = table(member_casual)) %>% 
ggplot(aes(member_casual, n, fill = member_casual, label = scales::percent(pct)))  
geom_col(position = "dodge")  
geom_text(position = position_dodge(width = .9), vjust = 10, size = 5)  
scale_y_continuous()  
labs(title = "Casual Vs Subscriber", x = "Rider type", y = "Rider count")   theme_gdocs()

dput is:

structure(list(X = 1:6, ride_id = c("CFA86D4455AA1030", "30D9DC61227D1AF3", 
"846D87A15682A284", "994D05AA75A168F2", "DF7464FBE92D8308", "CEBA8516FD17F8D8"
), rideable_type = c("classic_bike", "classic_bike", "classic_bike", 
"classic_bike", "classic_bike", "classic_bike"), member_casual = c("casual", 
"casual", "casual", "casual", "casual", "casual"), started_at = c("2021-03-16 08:32:00", 
"2021-03-28 01:26:00", "2021-03-11 21:17:00", "2021-03-11 13:26:00", 
"2021-03-21 09:09:00", "2021-03-20 11:08:00"), ended_at = c("2021-03-16 08:36:00", 
"2021-03-28 01:36:00", "2021-03-11 21:33:00", "2021-03-11 13:55:00", 
"2021-03-21 09:27:00", "2021-03-20 11:29:00"), time = c("08:32", 
"01:26", "21:17", "13:26", "09:09", "11:08"), month = c(3L, 3L, 
3L, 3L, 3L, 3L), day_of_week = c("Tuesday", "Sunday", "Thursday", 
"Thursday", "Sunday", "Saturday"), year = c(2021L, 2021L, 2021L, 
2021L, 2021L, 2021L), day = c(16L, 28L, 11L, 11L, 21L, 20L), 
trip_duration = c(240, 600, 960, 1740, 1080, 1260)), row.names = c(NA, 
6L), class = "data.frame")

I can't figure out how to get the total number of both bars added together to show up on the graph. I don't need the individual count, i need the total number. I saw some other questions that show the individual counts for each bar - I need the total.

CodePudding user response:

Are you looking for something like this?

(Note that I altered your data frame a little because all your member_casual values in the reprex were "casual")

all_trips2 %>% 
  count(member_casual) %>% 
  mutate(pct = prop.table(n), total = table(member_casual)) %>% 
  ggplot(aes(member_casual, n))  
  geom_col(aes(fill = member_casual), position = "dodge")  
  geom_text(aes(label = scales::percent(pct)),
    position = position_dodge(width = .9), vjust = 10, size = 5)  
  geom_text(aes(x = 1.5, y = max(n), 
                label = paste('Total =', sum(n))), size = 5, vjust = -0.5)   
  scale_y_continuous()  
  labs(title = "Casual Vs Subscriber", x = "Rider type", y = "Rider count")   
  theme_gdocs()

enter image description here

  • Related