4

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.

erc
  • 10,113
  • 11
  • 57
  • 88
Reb Gray
  • 87
  • 1
  • 4

1 Answers1

4

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

Duck
  • 39,058
  • 13
  • 42
  • 84
  • 1
    Please tell me what happened! – Duck Sep 09 '20 at 14:56
  • @RebGray Hi. Are all the labels in character format?? – Duck Sep 09 '20 at 15:00
  • @RebGray Hi Reb. I have added an update that uses numbers as you said in comments. Please check and let me know if that works for you :) – Duck Sep 09 '20 at 15:36
  • Hi - I posted a [follow-up question](https://stackoverflow.com/questions/63815731/how-to-pass-an-expression-to-a-geom-text-label-in-ggplot-continued) as I realized posting code in the comments is probably not good practice. I'll also look for your update - thanks! – Reb Gray Sep 09 '20 at 16:25