Confused about continuous transformations in ggplot2 - R

38 views Asked by At

I must be missing something trivial, but have already spent way too long on this, and thought someone might be able to help.

Say I want to plot the CDF for a random variable:

x = rnorm(100)
df <- data.frame(x = x, y = pnorm(x))
ggplot(df, aes(x=x, y=y)) + 
  geom_point()

enter image description here

If I now want to transform the axis into probit space, and maybe add a secondary axis showing z-scores, then I do:

ggplot(df, aes(x=x, y=y)) + 
  geom_point() + 
  scale_y_continuous(trans = "probit", sec.axis = sec_axis(trans = stats::qnorm))

enter image description here

Now say I only want to do the transformation to z-scores on the y-axis. This:

ggplot(df, aes(x=x, y=y)) + 
  geom_point() + 
  scale_y_continuous(trans = stats::qnorm)

returns:

Error in as.trans(): ! trans must be a character vector or a transformer object

I also tried:

ggplot(df, aes(x=x, y=y)) + 
  geom_point() + 
  scale_y_continuous(trans = transform_probability(distribution = "norm"))

which gives me the probit transformation above.

How do I specify stats::qnorm to be the transformation done to the main axis?

1

There are 1 answers

0
Mar On BEST ANSWER

Of course, as soon as I make the reproducible example an answer comes to me ‍♀️

Is this the only/best way to do it?

x = rnorm(100)
df <- data.frame(x = x, y = pnorm(x))

z_breaks = c(-2, -1, 0, 1, 2)

ggplot(df, aes(x=x, y=y)) + 
  geom_point() + 
  scale_y_continuous(
    trans = "probit", 
    breaks = pnorm(z_breaks), 
    labels = z_breaks
  )

enter image description here