Karl Wolfschtagg
Karl Wolfschtagg

Reputation: 567

ggplot multi-line log-log labels

I have some data I'm plotting like this:

g <- ggplot(datapile, aes(x = Re, y = CD))
g <- g + geom_line(data = datapile, linetype = "solid", size = 1)
g <- g + scale_y_continuous(trans='log10', limits = c(0.01, 400), n.breaks = 20)
g <- g + scale_x_continuous(trans='log10', limits = c(0.02, 1e7), n.breaks = 20)
g <- g + ylab(expression(Drag~Coefficient*","~C[D]))
g <- g + xlab(expression(Reynolds~Number*","~frac(rho~V~d, mu)))
g

It looks fine, but I'd like the numbers on the axis to appear like they do in this picture: sphere drag coefficient

Anyone know this offhand?

Upvotes: 2

Views: 50

Answers (1)

Jon Spring
Jon Spring

Reputation: 66880

library(ggplot2) 
library(ggtext) # to specify superscript etc. using html

# using a trick from https://stackoverflow.com/a/23902261/6851825
# "outer binary product" multiplies all combinations of the two vectors, 
#    concatenate to get vector of breaks
brks  <-  c(c(1,2,4,6,8) %o% 10^(0:10))
brks_log <- log10(brks)
labs <- ifelse(brks_log == floor(brks_log),
               paste0("<br>10<sup>", brks_log, "</sup>"),
               paste(brks / 10^floor(brks_log)))

ggplot(mtcars, aes(wt^5, mpg^3)) +
  geom_point() +
  scale_x_log10(breaks = brks, minor_breaks = NULL,
                labels = labs, guide = "axis_logticks") +
  theme(axis.text.x = element_markdown())

enter image description here

Upvotes: 5

Related Questions