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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 (cran.r-project.org/web/packages/wrapr/vignettes/bquote.html), but I want to learn more if the resources are easy to access
@wayner that gives a concise explanation. You can also check here or here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.