Search code examples
rggplot2subscriptsuperscript

ggplot2 axis text label: subscript + superscript + square brackets


I am trying to use subscript + superscript + square brackets in a Ggplot2 y-axis. But when I use below code, it shows error.

labs(y = parse(text = "S[in] ~~ group('[', W * ~~ m^-2, ']')"))

Error is:

Error in parse(text = "S[in] ~~ group('[', W * ~~ m^-2, ']')") : 
  <text>:1:3: unexpected 'in'
1: S[in
      ^

I need a label: Sin [W m-2], where in is subscript, and -2 is superscript.

Can anyone please help in fixing this issue?


Solution

  • You could use expression:

    library(ggplot2)
    ggplot(mtcars, aes(hp, mpg)) +
            geom_point() +
            labs(y = expression("S"["in"] ~ "[W" ~ m^-2~"]"))
    

    enter image description here