Search code examples
ggplot2plotexpression

How to make a superscript expression in ggplot2 legend


for some reason the expression I am trying to use for my legend isn't creating the superscript (using ggplot2). Could someone please direct me where I'm going wrong? I need to have the two lines as I want to maximize my plot area.

Reproducible example (although not in ggplot2):

plot(1:1, main=expression(paste('Mean driving\nspeed (km h^-1)')))

Thank you so much


Solution

  • The equivalent ggplot with the superscript using both expression() and ggtext (in the title, subtitle and legend):

    library(tidyverse)
    library(ggtext)
    
    df <- tibble(x = 1, y = 1)
    
    df |>
      ggplot(aes(x, y, colour = x)) +
      geom_point() +
      labs(
        title = "Mean driving<br>speed (km h<sup>-1</sup>)",
        # subtitle = expression(paste("km", h^-1)), # using expression
        colour = "Mean driving<br>speed (km h<sup>-1</sup>)"
      ) +
      theme(
        plot.title = element_markdown(),
        legend.title = element_markdown()
      )
    

    Created on 2024-04-12 with reprex v2.1.0