Search code examples
rggplot2expressiongeom-text

How to add a complex label with italics and a variable to ggplot?


I have read many postings on this topic using expression(), paste(), and bquote(), or some combination. I think I am close to solving my problem, but I just can't get there. The following script generates a plot labelled with "y = 1 + 2(x); r^2= 0.9". How can I italicize "y" and "x", and italicize the "r" and superscript the 2 of "r^2"? If I have overlooked a relevant earlier post, sorry, but please direct me to it.

df <- data.frame(x=c(1:5), y=c(1:5))
a <- 1    
b <- 2
r2 <- 0.9
eq <- paste("y = ", a, " + ", b, "(x); r^2=", r2)
ggplot(data=df, aes(x=x, y=y))+
  geom_point(color="black")+
  geom_text(x=2, y=4,label=eq, parse=FALSE)

Solution

  • You could use annotate() which allows you to paste directly into the plot.

    library(ggplot2)
    ggplot(data=df, aes(x=x, y=y)) +
      geom_point(color="black") +
      annotate('text', 2.5, 4, 
               label=paste("italic(y)==", a, "+", b, 
                           "~italic(x)~';'~italic(r)^2==", r2), 
               parse=TRUE, 
               hjust=1, size=5)
    

    Yields:

    enter image description here

    Data:

    df <- data.frame(x=c(1:5), y=c(1:5))
    a <- 1
    b <- 2
    r2 <- 0.9