llewmills
llewmills

Reputation: 3568

Two-line annotations using plotmath expressions in ggplot

I want to italicise a single character in the second line of a annotation in ggplot

Here's the plot

iris %>%
  ggplot(aes(x = Sepal.Length,
             y = Species,
             fill = Species)) +
         stat_summary(geom = "bar", fun = "mean") +
         theme(legend.position = "none") -> p

Now I can annotate the plot like so and get a single character italicised while the rest is unitalicised.

p + annotate("text", 
             label = "italic(N)==74",
             x = 3,
             y = 2,
             parse = T)  

enter image description here

Now say I want a two-line annotation with certain characters pasted in. I can do it this way without using plotmath

p + annotate("text", 
             label = paste("AUC = ", 
                           round(60.1876,3),
                           "\nN = ",
                           74,
                           sep = ""),
             x = 3,
             y = 2,
             size = 4)

enter image description here

As you can see the N character is unitalicised. Is there any way to get it looking like the second graph but with the N italicised, either using plotmath or some other technique?

Upvotes: 0

Views: 528

Answers (1)

Paul
Paul

Reputation: 9097

Use atop to draw text on top of text. See ?plotmath.

p +
  annotate(
    "text", 
    label = paste0("atop(AUC == ", round(60.1876, 3), ",italic(N) == 74)"),
    x = 3,
    y = 2,
    size = 4,
    parse = TRUE
  )

plot

Upvotes: 2

Related Questions