This is a follow-up my original question for how to pass an expression with subscript to a geom_text label in ggplot.
Duck provided a great solution using parse = T
within the geom_text()
command. However, I am now running into a problem because the variable I wish to pass an expression to contains other content that appears unreadable with parse = T
Here is my current code (again, thank you to Duck for this solution):
library(ggplot2)
library(tidyverse)
#Data
my_exp <- as.character(expression('my_exp'[s][u][b]))
my_data <-
data.frame(
var_1 = c("9R", "14M", "17C"),
var_2 = c(1, 2, 3),stringsAsFactors = F
)
#Mutate
my_data$label <- ifelse(my_data$var_1=='9R',my_exp,my_data$var_1)
#Plot
my_data %>%
ggplot(aes(x = var_1, y = var_2))+
geom_text(aes(label = label),parse = T)
And here is the error output that appears when I try to render the ggplot:
> library(ggplot2)
> library(tidyverse)
> #Data
> my_exp <- as.character(expression('my_exp'[s][u][b]))
> my_data <-
+ data.frame(
+ var_1 = c("9R", "14M", "17C"),
+ var_2 = c(1, 2, 3),stringsAsFactors = F
+ )
> #Mutate
> my_data$label <- ifelse(my_data$var_1=='9R',my_exp,my_data$var_1)
> #Plot
> my_data %>%
+ ggplot(aes(x = var_1, y = var_2))+
+ geom_text(aes(label = label),parse = T)
Error in parse(text = text[[i]]) : <text>:1:3: unexpected symbol
1: 14M
^
>
It appears R is having a hard time reading the cells where I have not passed the expression. Is there a way to have R only parse the relevant cell(s)?
Thanks!