Search code examples
rparsingggplot2expressiongeom-text

How to pass an expression to a geom_text label in ggplot? (Continued)


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!


Solution

  • As an alternative, you can use geom_richtext() from the ggtext package and create super- or subscripts with <sup>...</sup> or <sub>...</sub>.

    library(ggplot2)
    library(ggtext)
    
    #Data
    my_exp <- "my_exp<sub>sub</sub>"
    
    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
    ggplot(my_data, aes(x = var_1, y = var_2)) +
      geom_richtext(
        aes(label = label),
        # customization to remove background and border around labels
        fill = NA,
        label.colour = NA
      )
    

    Created on 2020-09-09 by the reprex package (v0.3.0)