Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Placing data labels for stacked bar chart at top of bar

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading