Search code examples
rmathggplot2facet

ggplot2 - Text and Math in Annotation with Facet


I'm trying to label the mean y value with its unit (m^2/ha) in a faceted plot in an annotation to the plot.

Answers have already been provided for the axis labels and the strip label, or for math only without text, but these answers do not work for annotation.

library(ggplot2)
my.df <- data.frame(grp=c("A", "A", "B", "B"), x=c(1,2,1,2),y=c(3,5,6,8))
my.avg <- data.frame(grp=c("A", "B"), mean=c(4,7))
p1 <- ggplot(my.df, aes(x, y)) + geom_point() + facet_wrap(~grp)
p1 <- p1 + geom_text(data=my.avg, aes(x=1.5, y=7, label=paste("Avg =", mean, "m2/ha")))
p1

where m2/ha is with the superscript.
I can make it work without "Avg =".
I tried expression(), but it doesn't work in this particular case.
What is the right function here?


Solution

  • try

    geom_text(data=my.avg, aes(x=1.5, y=7, label=paste("Avg ==", mean, "*m^2/ha")), parse=TRUE)