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

How to add a value label in each grouped barplot in ggplot2

This is the data I have:

totaldt <- data.frame(
  year = c(2023, 2022, 2021, 2023, 2022, 2021), 
  var = structure(c(1L, 1L, 1L, 2L, 2L, 2L), levels = c("knowrate", "outrate"), class = "factor"), 
  rate = c(0.616693826, 0.60826895, 0.611211938, 0.795008913, 0.820111343, 0.808219178)
)

First time using dput, sorry if I made a mistake. I am trying to add a value label in each group from the plot that I made. So, I want the respective value to show on top of each bar.
The code I am using is:

library(ggplot2)
ggplot(data = totaldt, aes(fill=(factor(year)), y=rate, x=var)) +
  geom_bar(stat="identity", position = "dodge", width=.5) +
  geom_text(aes(label=rate),
            angle=90,
            check_overlap = TRUE,) +
  labs(title = "Rates, MU Total",
       x = "",
       y = "Percentage",
       fill="Year") 

Which results in the following plot:

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

enter image description here

However, only one value is appearing and it appears in the wrong spot. Notice that the value appearing is relative to the year 2023, and it is on top of 2022 (green). How can I make all values appear on top of each respective bar? I hope I am making my question clear.

>Solution :

You need to dodge the text as well

ggplot(data = totaldt, aes(fill=factor(year), y=rate, x=var)) +
  geom_col(position = position_dodge(width=.6), width=.5) +
  geom_text(aes(label=rate),
            angle=90,
            check_overlap = TRUE, position = position_dodge(width=.6)) +
  labs(title = "Rates, MU Total",
       x = "",
       y = "Percentage",
       fill="Year") 

enter image description here

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