1

I've tried two approaches in trying to insert a text within my plot, to specify R² and the slope of a regression within a ggplot2 plot.

Important is first of all R² with the 2 as superscript, that I've saved its value and the value of the slope in variables I have to call, that the units of the slope is nmol/g*h which I want to display as nmol⋅g⁻¹⋅h⁻¹, and that R² and the slope should be displayed in two lines aligned left, in the top left corner of the plot.

I've tried the following:

  • Using expression, paste, and unicode:
text <- 
   expression(paste(
      paste(R^2, "=", r_squared, sep = " "), 
      paste("Slope =", slope, "nmol\u22c5g\u207B\u00B9\u22c5h\u207B\u00B9", sep = " "),
      sep = "\n"
   ))
  • Using bquote and atop:
text <- 
   bquote(atop(
     R^2 == .(r_squared_singledata),
     "Reaction rate" == .(slope_singledata)~nmol%.%g^-1%.%h^-1))

In both ways I've saved those expressions in a variable and called in later:

info_box <- grobTree(textGrob(text, x = 0.01, y = 0.99, 
                                hjust = 0, vjust = 1, gp = gpar(fontsize = 8)))
ggplot(data = mydata, aes(x,y))+
annotation_custom(info_box)

The problem is, that in the first way, I get a conversion error due to the unicodes. And in the second way, the text is centered rather then aligned left.

I've found a similar question here, but I can't adapt it to work for my problem...

Does anybody know a way to use exponents and variables in a two-lined text within a plot, that can be aligned left and positioned wherever I like?

the_ermine
  • 37
  • 6

1 Answers1

0

Okay so for reference in case somebody wants to do something similar:

There is actually no need to use complicated and fancy expressions when defining the text. Just use the richtext_grob() command from the gridtext package, which enables to use HTML and Markdown commands within a string.

My solution now looks like this:

library(gridtext)

# The <br> causes a line-break, <sup> and </sup> enter and escape superscript
text <- paste(
      paste("R<sup>2</sup> = ", r_squared),
      "<br>",
      paste("Slope = ", slope, " nmol g<sup>-1</sup> h<sup>-1</sup>")
    )

# Use of richtext_grob() instead of textGrob()
info_box <- grobTree(
        richtext_grob(text, x = 0.01, y = 0.99, 
                      hjust = 0, vjust = 1, gp = gpar(fontsize = 8))
        )

ggplot(data = mydata, aes(x,y))+
annotation_custom(info_box)

Other possibilities to format the text can be found here or on the official CRAN site.

the_ermine
  • 37
  • 6