2

I've just been advised to use the method trans_new in r's scales package to transform a plot's x axis using cubed root. I'm using trans_new to define a cubed root function and then using that cubed root function to transform the x axis (presumably this exercise is more academic than practical).

I've learned through trans_new's documentation that the method requires a transform argument and an inverse argument. The transform argument speaks for itself--through it, I define the transformation I want to apply to my data.

The inverse argument has me scratching my head, though. The documentation mentions what the argument does, but it doesn't say anything about why the argument is necessary.

inverse: function, or name of function, that performs the inverse of the transformation

The general description sounds a bit like it might be detailing the function of the inverse argument, but I'm not sure that's the case:

and it's expected that the labels function will perform some kind of inverse tranformation on these breaks to give them labels that are meaningful on the original scale.

Labels function? "Some kind of" inverse transformation?

A Google search has borne no fruit, so I would greatly appreciate anyone's help understanding why trans_new requires an inverse argument. What exactly is that argument doing?

Ryan Keeler
  • 41
  • 1
  • 5

1 Answers1

7

It means that if your transform function was base::log then your inverse function would be base::exp

my_new_transform <- trans_new(name = "test",
                              transform = base::log,
                              inverse = base::exp,
                              breaks = c(1, 10, 100))

As it says in the documentation, this is required for labeling the breaks apparently.

You can then go along and use coord_trans with ggplot2 to use this scale on your plot.


Example

library(scales)
library(ggplot2)

cube_root <- function(x) x ^ (1/3)
cube <- function(x) x ^ 3

trans_cube <- trans_new(name = "cube root",
                        transform = cube_root,
                        inverse = cube)

# dummy data
plot_data <- data.frame(x = 1:10,
                        y = cube(1:10))

# without applying a transform
ggplot(plot_data, aes(x = x, y = y)) +
  geom_point()

enter image description here

# applying a transform
ggplot(plot_data, aes(x = x, y = y)) +
  geom_point() +
  coord_trans(y = trans_cube)

enter image description here

zacdav
  • 4,603
  • 2
  • 16
  • 37
  • thanks for the great example. What if I want to do a Box-Cox transformation and share lambda between the transformation and its inverse? – PaulDong Apr 04 '20 at 03:52