rggplot2mathplot

Maths font for letter (e.g. x) in R ggplot legends


I want to have a plot with a legend displaying x_0, with a font that looks "mathematical" for x (I don't know how to say that otherwise), like 𝒙_0.

When I use expression(x[0]), this is what I get :

enter image description here

How can I get a font for x that doesn't look like a basic cross like this ?


Solution

  • My first idea on this was to use unicode, but this requires the user to either know them by heart or search them on the internet. So I thought why not use extrafont to load in a Calligraphic font for math text and a normal font like Calibri for normal non-math Text for italic and then mix them both together in expression('x'[italic('0')])

    library(ggplot2)
    library(extrafont)
    library(showtext)
    
    #system.fonts <- systemfonts::system_fonts() # look into your system's fonts
    
    font_add("LucidaCalligraphy-Italic", "LCALLIG.TTF", italic = "calibri.ttf") # LaTeX uses Calligraphic for MathCal
    
    showtext_auto()
    
    ggplot(data.frame(
      x = c(1,2),
      y = c(1,2),
      group = c("A", "B")
    ), aes(x = x, y = y, color = group)) +
      geom_point() +
      labs(color = expression('x'[italic('0')])) + 
      theme(text = element_text(size = 22),
            legend.title = element_text(family = "LucidaCalligraphy-Italic"))
    

    giving

    out