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:
CodePudding user response:
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