Superscripts in legend title ggplot2

Hello,

I want to add superscripts to my legend title but nothing I do seems to work. I want the legend title to say "Density (indiv m-3)" with the m-3 as the superscript. This is the line of code that I have to combine the size and color aesthetics into one legend (using guides()) and then labeling the legend "Density (indiv m-3)".

guides(color='legend', size='legend') + #combine size and color aesthetics into one legend
labs(color = bquote('Density'~(indiv m^(-3))), size = bquote('Density'~(indiv m^(-3)))) 
# label legend with superscripts

But I keep getting error messages such as:

Error: unexpected symbol in:
"    guides(color='legend', size='legend') +
    labs(color = bquote('Density'~(indiv m"
> }
Error: unexpected '}' in "}"

I'm sure it's a really simple fix that I'm just not seeing. Can somebody help?

Thanks so much!

Here is a way to add a superscript to a legend title using the ggtext package.

library(tidyverse)
library(ggtext)

ggplot(mtcars, aes(x = disp, y = hp, color = hp, size = am)) +
  geom_point() +
  scale_color_continuous(name = 'Density (indiv m<sup>-3</sup>)') +
  scale_size_continuous(name = 'Density (indiv m<sup>-3</sup>)') +
  theme(legend.title = element_markdown())

Created on 2023-01-11 with reprex v2.0.2.9000

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.