Search code examples
rggplot2axis-labels

Generating compact scientific notation with ggplot2 on R


The plots I generate with ggplot2 look like the one on the left with the full scientific notation on each tick of the y axis. How can I get it to look more compact like the plot on the right, which has the scientific notation labeled in the corner as circled in red?

I have not seen this mentioned in the ggplot2 package documentation or on stack overflow. Does anyone have a workaround?

two formats for scientific notation


Solution

  • Starting with a similar plot:

    ggplot(mtcars, aes(wt, mpg * 1E-8)) +
      geom_point()
    

    enter image description here

    If we know the scale we want to use, we could define it, and then we could either scale the data on the way in, or change the labels on the y axis, will look the same, except for y axis label (which we could rename whatever we want):

    divisor = 1E-8
    
    ggplot(mtcars, aes(wt, mpg * 1E-8 / divisor)) +
      geom_point() +
      labs(title = formatC(divisor, format = "e", digits = 0))
    

    enter image description here

    ggplot(mtcars, aes(wt, mpg * 1E-8)) +
      geom_point() +
      scale_y_continuous(labels = function(x) x / divisor) +
      labs(title = formatC(divisor, format = "e", digits = 0))
    

    enter image description here


    Edit:

    If you also want a title, you could alternatively use annotate to write the text outside the plot area, and then scootch the title up:

    ggplot(mtcars, aes(wt, mpg * 1E-8)) +
      geom_point() +
      scale_y_continuous(labels = function(x) x / divisor) +
      annotate("text", x = -Inf, y = Inf, hjust = 0, vjust = -0.5,
               label = formatC(divisor, format = "e", digits = 0)) +
      coord_cartesian(clip = "off") +
      labs(title = "Title here") +
      theme(plot.title = element_text(margin = margin(0,0,20,0)))
    

    enter image description here