Search code examples
rsubscript

adding subscripts to a character vector that will be used as a ggplot label


I see a lot of examples for getting subscripts and superscripts into plot labels, but I'm curious how to add a subscript to a character vector that can eventually be used for a plot.

Example data and plot:

 data.frame(site = LETTERS[1:10],
            a1 = c(rep(1, 7), rep(NA, 3)),
            a2 = c(rep(NA, 4), rep(2, 6)),
            minY = sample(1:9, 10, replace = TRUE),
            maxY = sample(10:19, 10, replace = TRUE)) %>% 
 mutate(label = case_when(is.na(a1) ~ paste(site, a2, sep = ""), 
                          is.na(a2) ~ paste(site, a1, sep = ""), 
                          TRUE ~ paste(site, paste(a1, a2, sep = ","), sep = ""))) %>% 
 ggplot() +
 geom_segment(aes(x = label, xend = label, y = minY, yend = maxY))

enter image description here

How can I made the 1's and 2's into subscripts for the plot?


Solution

  • We convert the label to latex and use TeX on that. DF is the data frame defined in the question, also shown in the Note at the end.

    library(dplyr)
    library(ggplot2)
    library(latex2exp)
    
    DF %>% 
      ggplot() +
      geom_segment(aes(x = label, xend = label, y = minY, yend = maxY)) +
      scale_x_discrete(labels = ~ TeX(sub("(.)([0-9,]+)", "$\\1_{\\2}$", .x)))
    

    screenshot

    Note

    This is as in the question except we have separated it out and named it DF.

    DF <- data.frame(site = LETTERS[1:10],
                a1 = c(rep(1, 7), rep(NA, 3)),
                a2 = c(rep(NA, 4), rep(2, 6)),
                minY = sample(1:9, 10, replace = TRUE),
                maxY = sample(10:19, 10, replace = TRUE)) %>% 
     mutate(label = case_when(is.na(a1) ~ paste(site, a2, sep = ""), 
                              is.na(a2) ~ paste(site, a1, sep = ""), 
                              TRUE ~ paste(site, paste(a1, a2, sep = ","), sep = "")))