rggplot2expressiongeom-text

How do you add both data frame values and math operators to geom_text in R?


I'm attempting to use geom_text to create a label 'Ankle Absorption W = -0.52 - 0.13 x Hop Height'. My understanding is that I need to use %*% within expression() to output the x sign. The numbers are stored in a data frame. I'm having difficulty getting expression() to read the data frame values - it simply prints the data frame name.

Here's my current code:

ggplot(mtcars, aes(hp, wt)) + 
    geom_text( label = expression( 'Ankle Absorption W = ' 
    mtcars$hp[1],' ', mtcars$hp[2] %*% 'Hop Height' ) )

The result for the mtcars$hp[1] portion was simply printing 'mtcars$hp[1]' rather than the stored values.

I've looked at other posts and tried using bquote() and paste() within expression() but it just prints 'bquote' and 'paste'.


Solution

  • Here's an example using ggtext with a standard data set (with shorter variable names):

    ggplot(mtcars, aes(hp, wt)) +
      ggtext::geom_richtext(aes(label = glue::glue("{hp} × {wt}")), 
                            fill = NA, label.color = NA)
    

    enter image description here