ggplot legend superscript

Using expression seems a good way to go, but you have trouble getting a vector (since expression won't evaluate format, so will dump the input vector all at once in a single expression). A solution is to use parse(text = ...) or equivalently str2expression() to execute format, make a string with paste, then turn it into an expression.

One caveat is that the expression has to be valid, so you need an operator (e.g. * or ~) between the number and the unit. This works on a different example:

labels = function(x) str2expression(paste0(format(round(x, 0), nsmall = 0), " ~ tun/km^2"))
3 Likes