How can I subscript and superscript my labels? I can't seem to get it working for ggdensity plots

3.5k Views Asked by At

I want to subscript the '2' in 'NO2' in the main heading and the xlabel, and I want to add '(µg/m3)' (with a superscript '3') in the xlabel, but the way I did it before for histograms doesn't work. Any help would be gratefully received! This is what I have so far:

library(ggpubr)

ggdensity(bgbind$no2,
main = "Density plot of background NO2 concentrations",
xlab = "NO2")
2

There are 2 best solutions below

1
On

You can just use the symbols directly:

ggdensity(bgbind$no2, 
          main = "Density plot of background NO₂ concentrations", 
          xlab = "NO₂ (µg/m³)") 

A somewhat more portable way of doing this is using unicode escape sequences. I tend to do this by looking up, say, "unicode subscript 2" in a web search engine. This will usually give you the result in the format "U+AAAA" where "AAAA" is a four digit hexadecimal number. If you do "\uAAAA" as a string in R, this will be converted to the appropriate unicode symbol. So, for example, look at what prints in the console here:

"NO\u2082 (\u03BCg/m\u00bB)"
#> [1] "NO₂ (μg/m»)"
5
On

You can use bquote().

Here is an example with ggplot2:

library(ggplot2)

bgbind <- data.frame(
  no2 = 1:10,
  y = 1:10
)

ggplot(bgbind, aes(no2, y)) +
  geom_point() +
  labs(title = bquote("Density plot of background NO"[2] ~ "concentrations"),
       x = bquote(NO[2] ~ (mu*g/m^3)))

Assuming that, by main, you meant the title of the plot.

enter image description here

I cannot test it as I don't have your dataset and I am unable to install the package ggpubr for some reason, but in your situation, this should work:

library(ggpubr)

ggdensity(bgbind$no2,
          main = bquote("Density plot of background NO"[2] ~ "concentrations"),
          xlab = bquote(NO[2] ~ (mu*g/m^3)))

Inside bquote(), [] subscripts what is inside, ^ superscripts what follows, ~ adds a space, mu is turned into the symbol micro, * juxtaposes 2 elements.