Search code examples
rformattingnotation

Force R to write scientific notations as n.nn x 10^-n with superscript


Let's say I have two floats

a <- 8.9384920e-24
b <- 0.00293892837

I would like to display either of them in 10-base scientific notation rounded to two decimals on a graph, possibly using paste(), but with superscript formatting after the 10.

8.94 x 10^-24 #no ^ and superscript font
2.94 x 10^-4  #no ^ and supercript font, should be -4, not -04

This is really maniac but it has been requested by a superior, it has to be done in base R (not ggplot2) or I will have to re-write 600 lines of code... Right now all I can see is that floats are printed differently depending on how big they are...


Solution

  • You may check eaxis in package sfsmisc

    # some data
    x <- seq(1, 100000, len = 10)
    y <- seq(1e-5, 1e-4, len = 10)
    
    # default axes
    plot(x, y)
    

    enter image description here

    # eaxis
    plot(x, y, axes = FALSE)
    eaxis(side = 1)
    eaxis(side = 2)
    

    enter image description here

    You may also create a label expression using pretty10exp() from the same package. For example to apply the format to a plot title:

    plot(x, y, axes = FALSE)
    title(pretty10exp(y[1]))
    

    enter image description here