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

Annotate ggplot with superscripts and subscripts with commas

I’m trying to annotate my ggplot with three lines. I’ve given up trying the atop() way because I have three lines and each line has a superscript or subscript and I keep running into errors.

I would like to alter the following annotations on this plot:

  • the "149" should read "1,49" in subscript
  • the "R2adj" should have the 2 superscript and the adj subscript.

ggplot with errors

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

mod1 <- lm(data = mtcars, mpg ~ cyl)
F_stat <- (car::Anova(mod1))$`F value`[1]

ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  annotate(geom = 'text',
         x = 4,
         y = 30, 
         label = paste("F[149] ==", F_stat), 
         parse = TRUE,
         hjust = 0) +
  annotate(geom = 'text',
         x = 4,
         y = 25, 
         label = paste("p < 0.001"), 
         parse = TRUE,
         hjust = 0) +
  annotate(geom = 'text',
         x = 4,
         y = 20, 
         label = paste(
           "R^2",
           "[adj]",
           "==",
           round(summary(mod1)$adj.r.squared, 3)), 
         parse = TRUE,
         hjust = 0)

I’ve looked at several other stackoverflow posts and cannot figure it out. Any advice? Thank you!

>Solution :

To get the adj in subscript and the 2 in superscript, try R[adj]^2 instead of R^2[adj]. To get a comma in the subscripted number, wrap the number in quotes. You’ll need a backslash escape for the quotes, so it’s paste("F[\"1,49\"] ==", 122.952)

ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  annotate(geom = 'text',
           x = 4,
           y = 30, 
           label = paste("F[\"1,49\"] ==", 122.952), 
           parse = TRUE,
           hjust = 0) +
  annotate(geom = 'text',
           x = 4,
           y = 25, 
           label = paste("p < 0.001"), 
           parse = TRUE,
           hjust = 0) +
  annotate(geom = 'text',
           x = 4,
           y = 20, 
           label = paste(
             "R[adj]^2",
             "==",
             0.709), 
           parse = TRUE,
           hjust = 0)

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