Search code examples
rggplot2legendsubscript

Subscript legend text in ggplot (R) after using paste() to create variable values


I am trying to plot some data with ggplot2. With geom_point some special characteristics of the model fit (e.g. maximum of a quadratic function) should be highlighted. Due to the fact, that the characteristics of some model fits just differ slightly, the x and y coordinates of the characteristics should be displayed in the legend. Besides the values also some text should be displayed in the variable names of the legend.
So far everything works.
But when I try to subscript parts of the text, I find no solution working. Also with the solution of using subscript in legend I failed until now.

This is my code in simplified form:

library(tidyverse)

data <- tibble(
  text = rep(
    c("text1", "text2"), 
    each = 2
    ),
  x = rep(
    c(1,2,0.5,0.75)
    ),
  y = rep(
    c(2,4,1.8,3.6)
    ),
  group = rep(
    c("one", "two")
    , each = 2
    )
  ) %>%
  mutate(
    name = case_when(
      group == "one" ~ paste(
        text, ":", "X[sub1]", " = ", sprintf("%.1f",round(x,1)), "; Y[sub1] = ", sprintf("%.1f",round(y,1))
        ),
      group == "two" ~ paste(
        text, ":", "X[sub2]", " = ", sprintf("%.1f",round(x,1)), "; Y[sub2] = ", sprintf("%.1f",round(y,1))
        ),
      TRUE ~ NA_character_
      )
    ) 


plot_ <- ggplot(
  data = data, 
  aes(
    x=x, 
    y=y, 
    shape = group, 
    color = name)
  )+
  geom_point(
    size = 3
    )

plot_

I'm looking for a solution, where sub1 and sub2 in the legend text don't appear in square bracket, but as subscripts.


Solution

  • I would recommend using {ggtext} for formatting of any text. Switch from using [] to <sub></sub>, and specify that it should be an element_markdown in the theme:

    library(tidyverse)
    library(ggtext)
    
    data <- tibble(
      text = rep(
        c("text1", "text2"), 
        each = 2
      ),
      x = rep(
        c(1,2,0.5,0.75)
      ),
      y = rep(
        c(2,4,1.8,3.6)
      ),
      group = rep(
        c("one", "two")
        , each = 2
      )
    ) %>%
      mutate(
        name = case_when(
          group == "one" ~ paste(
            text, ":", "X<sub>sub1</sub>", " = ", sprintf("%.1f",round(x,1)), "; Y<sub>sub1</sub> = ", sprintf("%.1f",round(y,1))
          ),
          group == "two" ~ paste(
            text, ":", "X<sub>sub2</sub>", " = ", sprintf("%.1f",round(x,1)), "; Y<sub>sub2</sub> = ", sprintf("%.1f",round(y,1))
          ),
          TRUE ~ NA_character_
        )
      ) 
    
    
    plot_ <- ggplot(
      data = data, 
      aes(
        x=x, 
        y=y, 
        shape = group, 
        color = name)
    )+
      geom_point(
        size = 3
      ) +
      theme(legend.text = element_markdown())
    
    plot_
    

    gives:

    enter image description here