R - Interpretation of the index in the variable used in ggplot

I am using ggplot to generate several multi-line plots that are plotted with a lot of variables and using paste. I was unable to figure out how to get index 3 in O3 so that it appears in the next 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 at index 3.


source to share

2 answers

The problem is that you need the label on the scale to be an expression so that when it is rendered it will display according to the rules plotmath

. However ggplot

works with data.frame

and data.frame

cannot have a column that is an expression vector. So the way around this is to store the information as a text (string) version of the expression plotmath

and, as a final step for creating labels, turn them into expressions. This can be done as the argument labels

to the scaling functions itself can be a function that can convert / format labels.

Putting this alongside your example:

color1 <- paste(gasSubscript,"*\" some additional text\"")


It is now a format that can be converted to 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")


In this format, you can force the scale to interpret the labels as expressions that will make them render according to the rules plotmath


testPlot <- ggplot(data = df, aes(x = x)) + 
  geom_line(aes(y = y, color = color1)) +
  scale_colour_discrete(labels = function(x) parse(text=x))


enter image description here

Using a functional approach labels

works for data that is also stored in data.frame

if 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))


enter image description here



This should do what I think you want. It took me a bit of tinkering to get the paste and expression order correct.

test <- 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))
colour1 <- "1"

testPlot <- ggplot(data = test, aes(x = x)) + geom_line(aes(y = y, colour = colour1))
testPlot + scale_colour_discrete(labels = c(expression(paste(O[3], "some other text here"))))


Subscript legend label

It also returns a warning

Warning message:
In is.na(scale$labels) :
  is.na() applied to non-(list or vector) of type 'expression'


to which I could not find an explanation.



All Articles