Home > Mobile >  Placing data labels for stacked bar chart at top of bar
Placing data labels for stacked bar chart at top of bar

Time:11-01

I have been attempting to add a label on top of each bar to represent the proportion that each ethnic group makes up in referrals.

For some reason I cannot get the labels to be placed at the top of each bar. How do I fix this?

My code below

freq <- df %>%
  group_by(ethnicity) %>%
  summarise(n = n()) %>%
  mutate(f = round((n/sum(n)*100, 1))

df %>%
    group_by(pathway) %>%
    count(ethnicity) %>%
 
  ggplot(aes(x = ethnicity, y = n , fill = pathway))  
    geom_bar(stat = "identity", position = "stack")  
    geom_text(data = freq, 
              aes(x= ethnicity, y = f, label = f), 
              inherit.aes = FALSE)  
    theme(legend.position = "bottom")  
    scale_fill_manual(name = "",
                      values = c("light blue", "deepskyblue4"),
                      labels = "a", "b")  
    xlab("")  
    ylab("Number of Referrals")  
    scale_y_continuous(breaks = seq(0, 2250, 250), expand = c(0,0)          

Here is what it currently looks like enter image description here

CodePudding user response:

Since you are using the count as your y-axis position in geom_bar, you need to use the same thing in your geom_text to get the labels in the right place. Below is an example using mtcars dataset. Using vjust = -1 I put a little bit of space between the label and the bars to make it more legible and aesthetically pleasing.

library(tidyverse)

mtcars %>% 
  group_by(carb) %>% 
  summarise(n = n()) %>% 
  mutate(f = round(proportions(n) * 100, 1)) -> frq

mtcars %>% 
  group_by(gear) %>% 
  count(carb) -> df

df %>% 
ggplot(aes(x = carb, y = n, fill = gear))  
  geom_bar(stat = "identity", position = "stack")  
  geom_text(data = frq, 
            vjust = -1,
            aes(x= carb, y = n, label = f), 
            inherit.aes = FALSE)

Created on 2022-10-31 by the reprex package (v2.0.1)

  • Related