The problem is that you need the label in the scale to be an expression so that, when it is rendered, it is rendered according to the rules of plotmath
. However, ggplot
works with data.frame
s and data.frame
s can not have a column which is a vector of expressions. So the way around this is to store the information as the text (string) version of the plotmath
expression and, as the last step for making the labels, turn these into expressions. This can be done because the labels
argument to the scale functions can itself be a function which can transform/format the labels.
Putting this together with your example:
color1 <- paste(gasSubscript,"*\" some additional text\"")
This is now in a format that can be made into an expression.
> color1
[1] "O[3] *\" some additional text\""
> cat(color1)
O[3] *" some additional text"
> parse(text=color1)
expression(O[3] *" some additional text")
With that format, you can force the scale to interpret the labels as expressions which will cause them to be rendered as per the rules of plotmath
.
testPlot <- ggplot(data = df, aes(x = x)) +
geom_line(aes(y = y, color = color1)) +
scale_colour_discrete(labels = function(x) parse(text=x))

Using the labels
function approach works for data which is stored in the data.frame
as well, so long as the strings are formatted so that they can be parsed.
DF <- data.frame(x=1:4, y=rep(1:2, times=2),
group = rep(c('O[3]*" some additional text"',
'H[2]*" some different text"'), each = 2))
ggplot(DF, aes(x, y, colour=group)) +
geom_line() +
scale_colour_discrete(labels=function(x) parse(text=x))
