jack kelly
jack kelly

Reputation: 330

Paste string with superscript in ggplot

I am trying to pass a variable toPaste which is a string that I want part of it to be superscripeted. The string: "this^2/that^+" where 2 and + are desired to be superscripted.

I browsed around, and it seems, I need to reformat my string, and then I can paste() in a bquote() for example, but since the desired superscript is embedded in the middle of the string, I am not sure how to approach it. Sample script below:

library(ggplot2)
toPaste <- "this^2/that^+"
ggplot() + ylab(toPaste)

Any assistance is appreciated.

Upvotes: 0

Views: 1216

Answers (4)

elkalamaras
elkalamaras

Reputation: 106

You can use the following:

toPaste <- "this^2/that^'+'"
ggplot() + ylab(parse(text = toPaste))

Note that the "+" sign needs to be surrounded by single quotes.

Upvotes: 2

TarJae
TarJae

Reputation: 78917

An alternative is to use expression:

ggplot() + ylab(expression(this^2/that^"+"))

enter image description here

Upvotes: 1

Mossa
Mossa

Reputation: 1709

The answer is in bquote:

ggplot() + ylab(bquote(this^2/that^"+"))

Upvotes: 0

Josh Allen
Josh Allen

Reputation: 1280

You can use latex2exp to use LaTeX for stuff like this

library(ggplot2)
library(latex2exp)

data("mtcars")

ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point() +
  labs(title = TeX("Title: $\\frac{this^{2}}{\\that^{+}}$"))

Created on 2022-05-26 by the reprex package (v2.0.1)

Upvotes: 2

Related Questions