ggplot2 axis text formatting won't work with exponents

587 Views Asked by At

It is easy enough to change the axis text of a ggplot to some sort of expression (in this case 10^.x). However, when the text is transformed, it loses bold formatting.

I was wondering if there was a way to retain bold formatting but also have the exponent labelling shown below.

library(ggplot2)

xxx <- data.frame(
  x = c(-5, -4, -3),
  y = c(1, 1, 1)
)

ggplot(xxx, aes(x, y)) + 
  geom_point() + 
  scale_x_continuous(label = scales::label_math(expr = 10^.x)) + 
  theme_bw(base_size = 20) + 
  theme(axis.text = element_text(face = "bold"))

Created on 2020-08-31 by the reprex package (v0.3.0)

1

There are 1 best solutions below

0
On

I solved my own problem just after posting this. I adapted the make_labels function from an answer to this question.

The trick is to paste the axis numbers as text and then use bold (or italic or whatever) within an expression to control the formatting.

library(ggplot2)

xxx <- data.frame(
  x = c(-5, -4, -3),
  y = c(1, 1, 1)
)

exp_bold <- function(lab) {
  do.call(
    expression,
    lapply(paste(lab), function(x) bquote(bold("10"^.(x))))
  )
}

ggplot(xxx, aes(x, y)) + 
  geom_point() + 
  scale_x_continuous(label = exp_bold) + 
  theme_bw(base_size = 20) + 
  theme(axis.text = element_text(face = "bold"))

Created on 2020-08-31 by the reprex package (v0.3.0)