Search code examples
rggplot2markdownggtext

ggplot2 true minus sign with superscript in axis text


Related question: R: ggplot2 minus sign instead of hyphens (-) in ylim axis

I understand that the unicode glyph \u2212 may be substituted for the hyphen to get a true minus sign in ggplot2 axis text, as the answer to the above linked question says. However, I need to place the minus sign in a superscript. Usually I use ggtext::element_markdown() but if I place the Unicode glyph, or the HTML entity −, in between two ^^, nothing displays. If element_markdown() is not a workable solution I would appreciate any other way of getting a true minus sign in my negative exponents in ggplot2.

Example

library(ggplot2)
library(ggtext)

log_breaks <- 10^(-3:1)
log_labels <- c(paste0('10^\u2212', 3:1, '^'), '10^0^', '10^1^')
dt <- data.frame(x = 1, y = log_breaks)

ggplot(dt, aes(x, y)) + geom_point() + 
  scale_y_log10(breaks = log_breaks, labels = log_labels) +
  theme(axis.text.y = element_markdown())

log_labels appears to be correct:

[1] "10^−3^" "10^−2^" "10^−1^" "10^0^"  "10^1^"

But axis text with the Unicode glyph in it does not display. The same result occurs if &minus; is used instead of \u2212.

plot where negative exponents do not show up


Solution

  • You can use <sup>-1</sup>.

    log_labels <- c(paste0('10<sup>\u2212', 3:1, '</sup>'), '10^0^', '10^1^')
    ggplot(dt, aes(x, y)) + geom_point() + 
      scale_y_log10(breaks = log_breaks, labels = log_labels) +
      theme(axis.text.y = element_markdown())
    

    enter image description here