Search code examples
rmathscaleinverse

Inverse of 200000^x in R


I wanted to graph a secondary axis using ggplot, I multiply my original data with 200000^[whole column], what's the inverse of this?

scale_y_continuous(sec.axis = sec_axis(~.  ) )

Solution

  • Using Nico's math, here's a working example using the inverse:

    set.seed(2)
    z <- data.frame(x=1:100, y=200000^runif(100, 10, 11))
    
    ggplot(z, aes(x, y)) +
      geom_point() +
      scale_y_continuous(
        sec.axis = sec_axis(~ log(.) / log(200000), breaks=c(10.1,10.9, 10.95)),
        expand = c(0,0)
      )
    

    I had to use expand=c(0,0) because the expansion of the axis (common for context and clipping) resulted in negative values, even though there were no negative values in the data. These negatives resulted in warnings, so if you don't mind the warnings then you can exclude that. (There are likely other ways to deal with this phenomenon, perhaps they won't be necessary with your data.)

    sample ggplot graph with secondary axis

    Edit: I added breaks=. Note that breaks= and labels= can be overridden with numeric values or a function as input, so you don't need to hard-code the values as I have done here.