Search code examples
rggplot2plotmath

How to use bquote in combination with ggplot2 geom_label?


I've read the following article: https://trinkerrstuff.wordpress.com/2018/03/15/2246/

Now I'm trying to use the suggested approach with bquote in my plot. However I can't get it to work. I have the following code

x <- seq(0, 2*pi, 0.01)
y <- sin(x)
y_median <- median(y)
ggplot(mapping = aes(x = x, y = y)) + 
  geom_line() + 
  geom_label(aes(label = bquote("median" ~ y==~.y_median), x = 1, y = y_median))

I get the following error:

Error in as.data.frame.default(x[[i]], optional = TRUE) : 
  cannot coerce class ‘"formula"’ to a data.frame

What am I doing wrong?


Solution

  • ggplot doesn't like to work with expressions for labels in geom_text or geom_label layers. It likes to work with strings. So instead you can do

    ggplot(mapping = aes(x = x, y = y)) + 
      geom_line() + 
      annotate("text", label = deparse(bquote("median" ~ y==~.(y_median))), x = 1, y = y_median, parse=TRUE)
    

    We use deparse() to turn it into a string, then use parse=TRUE to have ggplot parse it back into an expression. Also I just used annotate() here since you aren't really mapping this value to your data at all.