Search code examples
rggplot2annotationsgeom-text

Adding a value to an expression and pasting it in ggplot2 with annotate


I have a piece of code like this:

f<-expression("3"*"±"*"2"~"kg"*"\U00B7"*yr^-1)

I want to replace the 3 and 2 (arbitrarily chosen values) with mean and st. dev., which are calculated automatically, so that when I do something like

mean<-mean(df$a)
stdev<-st.dev(df$a)
f<-expression(mean*"±"*stdev~"kg"*"\U00B7"*yr^-1)

and then use the annotate() function in ggplot2, like

+annotate(
  "text",
  x=55,
  y=43.2,
  label=f,
  parse=T
)

the Values of mean and stdev will be included in the annotation, rather than just the words "mean" and "stdev". Does anyone know how to resolve this, or perhaps a workaround? Thanks


Solution

  • One option would be to use paste0 to create your plotmath string like so:

    library(ggplot2)
    
    df <- data.frame(
      a = c(1, 2),
      b = c(1, 2)
    )
    
    mean <- mean(df$a)
    stdev <- sd(df$a)
    
    f <- paste0(mean, '* "±" * ', stdev, ' ~ "kg" * "\U00B7" * yr^-1')
    
    ggplot(df) +
      annotate(
        "text",
        x = 55,
        y = 43.2,
        label = f,
        parse = TRUE
      )