2

I am trying to create labels in ggplot that are comprised of character vectors and expressions combined into a single label. I want the characters and expressions to be sourced from objects so that I can easily use a function to swap them for different plots created using ggplot.

Unfortunately I lack the syntax knowledge needed to combine expressions stored in objects. My situation is described below:

library(ggplot2)

data(iris)

sup <- bquote(super^1)
sub <- bquote(sub[1])

ggplot() +
geom_point(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
labs(x = expression('Static text: '~sup~sub))

I have tried combinations of bquote(), quote(), substitute(), and I tried expression(paste('Main text', sup, sub). I also tried the eval() function to see if it would force the objects to be read as expressions inside the expression.

Because of my limited knowledge of syntax, I don't know what other options are available. It has been difficult to find advanced R resources that explain syntax for such specific situations so stack overflow has been the place I go to learn these things.

My main goal is to make it look like this, but importing text from an object instead of writing directly into the expression:

enter image description here

wayne r
  • 110
  • 1
  • 5

1 Answers1

4

We can wrap it within bquote

library(ggplot2)
ggplot() +
 geom_point(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
   labs(x = bquote('Static text: '~.(sup)~.(sub)))

-output

enter image description here

akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Thank you! I didn't know it would be this simple. Do you have a recommendation for where to learn this syntax? I searched for 'bquote wrap and found a useful blog post (https://cran.r-project.org/web/packages/wrapr/vignettes/bquote.html), but I want to learn more if the resources are easy to access – wayne r May 27 '22 at 18:53
  • 1
    @wayner that gives a concise explanation. You can also check [here](https://win-vector.com/2018/10/16/quasiquotation-in-r-via-bquote/) or [here](https://www.r-bloggers.com/2018/03/math-notation-for-r-plot-titles-expression-and-bquote/) – akrun May 27 '22 at 18:57