Search code examples
rggplot2expressionsubscriptgeom-text

How to pass an expression to a geom_text label in ggplot?


I am attempting to pass an expression with subscript to a single geom_text() label in ggplot. Here is my code right now:

my_exp <- expression('my_exp'[s][u][b])

my_data <- 
  data.frame(
    var_1 = c("a", "b", "c"),
    var_2 = c(1, 2, 3)
  )

my_data %>%
  ggplot(aes(x = var_1, y = var_2))+
  geom_text(aes(label = var_1))

Here is the resulting plot:

[Here is the resulting plot][1].

What I would like to do is replace the var_1 value of "a" with the expression specified by my_exp and then have geom_text() evaluate that value as an expression, resulting in the subscript appearing on the ggplot.


Solution

  • I would suggest this approach. You can build another variable for your labels and then enable the option parse=T from geom_text() in order to have the desired plot. Here the code:

    library(ggplot2)
    library(tidyverse)
    #Data
    my_exp <- as.character(expression('my_exp'[s][u][b]))
    
    my_data <- 
      data.frame(
        var_1 = c("a", "b", "c"),
        var_2 = c(1, 2, 3),stringsAsFactors = F
      )
    #Mutate
    my_data$label <- ifelse(my_data$var_1=='a',my_exp,my_data$var_1)
    #Plot
    my_data %>%
      ggplot(aes(x = var_1, y = var_2))+
      geom_text(aes(label = label),parse = T)
    

    Output:

    enter image description here

    Update: If there are issues with labels here a code for that:

    #Label
    my_exp <- "14~M~my_exp[s][u][b]"
    #Code
    my_data <- 
      data.frame(
        var_1 = c("a", "b", "c"),
        var_2 = c(1, 2, 3),stringsAsFactors = F
      )
    #Mutate
    my_data$label <- ifelse(my_data$var_1=='a',my_exp,my_data$var_1)
    #Plot
    my_data %>%
      ggplot(aes(x = var_1, y = var_2))+
      geom_text(aes(label = label),parse = T)
    

    Output:

    enter image description here