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

R: Is it possible to add labels to mean_cl_boot in ggplot?

I’m trying to add labels indicating the mean in a jitter plot, I’ve used the mean_cl_boot function in stat_summary and the means are showing on the plot, but I’d like to add labels showing the actual values and I’m at a bit of a loss.

Jitter plot

Here’s my code

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

lisbondata %>% 
  ggplot(aes(q1b,exage)) +
  stat_summary(fun.data = "mean_cl_boot",colour="red") +
  geom_jitter(alpha=0.2) +
  labs(title = "Age distribution between Yes/No votes",
        x = "Vote",
        y = "Age") +
  theme_bw()

>Solution :

You can combine different stats and geom together. If you have stat_summary(), you can combine it with geom_label() by setting geom = "label". You can then tell the label to be the mean value, by delaying the assignment of the label aesthetic using after_stat().

library(ggplot2)

ggplot(iris, aes(Species, Sepal.Length)) +
  geom_jitter(colour = "grey50") +
  stat_summary(
    fun.data = "mean_cl_boot", colour = "red"
  ) +
  stat_summary(
    fun.data = "mean_cl_boot",
    geom = "label",
    aes(label = after_stat(scales::number(y))),
    hjust = 1.2
  )

Created on 2022-02-19 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