Search code examples
rggplot2scaleaxis-labelsfacet-wrap

How to make y-scales in ggplot in R follow similar numbering format?


I would like to change the format of the y-axis numbers such that the axis-es follow similar numbering format. right now Facet A is plain while Facet B is scientific. I understand there are large difference in the values of the two facets which is why i use log scale make the low values more visible. I used labels = "scientific" to force the scale being scientific but is giving me error. here is my code- any help would be appreciated.

library(tidyverse)

DF = data.frame(A = runif(8000, 100,800), B = runif(8000, 0, 10), C = 1:8000)
DF_g = gather(DF, key = "Variable", value = "Value", - C)
ggplot(DF_g, aes(x = C, y = Value, color = Variable))+
  geom_boxplot(lwd = 1)+facet_wrap(~Variable, nrow = 2, scales = "free_y")+
  scale_y_continuous(trans = "log10")

The Figure i get from the code is enter image description here


Solution

  • You can use the function scientific_format() from scales:

    ggplot(DF_g, aes(x = C, y = Value, color = Variable))+
        geom_boxplot(lwd = 1)+facet_wrap(~Variable, nrow = 2, scales = "free_y")+
        scale_y_continuous(trans = "log10", labels = scales::scientific_format())
    

    enter image description here