Search code examples
rggplot2plotmath

Removing spaces in leading superscripts in ggplot2 axis titles and labels


Maybe i am not correct, but it appears to me that there is an undesired space in expressions beginning with a superscript:

df <- data.frame(treatment=as.factor(c("A", "B")), value=c(1,2))

labels <- c(expression(""^14~CH[4]),
            expression(""^14~CH[4]~"+"~"SO"[4]^{2-''}))

library(ggplot2)
ggplot(df, aes(treatment, value)) +
  geom_bar(stat="identity") +
  scale_x_discrete(labels=labels)

I could go to Photoshop to reduce the space between the superscripted 14 and the "C", but maybe there is a way in plotmath? Notice, that this is not happening in the second expression with a superscript in the end.enter image description here


Solution

  • In expressions, ~ gives you a space between terms. If you don't want a space between terms, you can use *. The end superscript is not preceded by a ~, so no space.

    You can also remove most of the quote marks - these are unnecessary except when there are special characters or spaces.

    So your expression can become

    expression(''^14*CH[4]~+~SO[4]^'2-')