0

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

M--
  • 25,431
  • 8
  • 61
  • 93
PhelsumaFL
  • 61
  • 8

1 Answers1

2

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
  )

stefan
  • 90,330
  • 6
  • 25
  • 51
  • this worked very well. Thank you very much. I have been plotting the annotations in bold (fontface=2). Strangely, when parse=T, the fontface option seems to stop working, and the text is no longer bold. Do you know why this is? Thank you – PhelsumaFL Mar 02 '23 at 08:30