I am trying to display subscripts in ggplot facet labels where there are mixed letters and numbers in the subscript using parse()
.
This works:
>parse(text="cI[933]")
And so does this:
>parse(text="cI[W]")
But not these:
>parse(text="cI[933W]")
Error in parse(text = "cI[933W]") : <text>:1:7: unexpected symbol
1: cI[933W
^
> parse(text="cI[9W33]")
Error in parse(text = "cI[9W33]") : <text>:1:5: unexpected symbol
1: cI[9W33
^
For an example in ggplot:
data(mtcars)
mtcars$cyl2 <- factor(mtcars$cyl, labels = c("cI[123]", "cI[ABC]", "cI[456]"))
qplot(wt, mpg, data = mtcars) + facet_grid(. ~ cyl2, labeller = label_parsed)
That works fine, but:
data(mtcars)
mtcars$cyl2 <- factor(mtcars$cyl, labels = c("cI[AB3]", "cI[2CD]", "cI[EF1]"))
qplot(wt, mpg, data = mtcars) + facet_grid(. ~ cyl2, labeller = label_parsed)
...does not.
This is failing because 2CD
is not a legal symbol according to the R parser (symbols must begin with an alphabetic character and must contain only alphanumeric + [._]
characters (I think)). As a quick workaround, you can protect the illegal symbols with single quotes:
mtcars$cyl2 <- factor(mtcars$cyl,
labels = c("cI[AB3]", "cI['2CD']", "cI[EF1]"))
The quotation marks don't show up in the plot labels.
From the introduction to R:
Normally all alphanumeric symbols are allowed (and in some countries this includes accented letters) plus ‘.’ and ‘_’, with the restriction that a name must start with ‘.’ or a letter, and if it starts with ‘.’ the second character must not be a digit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With