I'm using ggplot to do some multiline plots that are constructed with lots of variables and the use of paste. I have not been able to figure out how to get the subscript 3 in O3 to appear in the following simplified version of the code.
gasSubscript <- "O[3]"
color1 <- paste(gasSubscript,"some additional text")
df <- data.frame(x = c(1,2,3,4,5,6,7,8,9,10), y = c(10,9,8,7,6,5,4,3,2,1))
testPlot <- ggplot(data = df, aes(x = x)) + geom_line(aes(y = y, color = color1))
color1 contains
"O[3] some additional text"
The legend displays as "O[3] some additional text" rather than with a subscripted 3.
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))