Search code examples
rplotggplot2axes

ggplot secondary y axes showing z scores using sec_axis


ggplot2 now allows for adding a secondary y-axis if it is a one-to-one transformation of the primary axis.

For my graph, I would like to plot the original units on the left y-axis and z-scores on the right y-axis, but I am having trouble working out how to do this in practice.

The documentation suggests this secondary axes are added using the sec_axis() function e.g.,

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

creates a second y-axis 10 units higher than the first.

Z-scores can be created in R using the scale() function. So I assumed I could do something like this to get a second y-axis displaying z-scores:

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

However, this returns a "invalid first argument" error.

Does anyone have any ideas how to make this work?


Solution

  • You could use the z-score transformation formula. This works well:

    library(tidyverse)
    library(scales)
    df <- data.frame(val = c(1:30), var = rnorm(30, 10,2))
    p <- ggplot() + geom_line(data = df, aes( x = val, y = var))
    p <- p + scale_y_continuous("variable", sec.axis = sec_axis(trans = ~./ sd(df$var) - mean(df$var)/ sd(df$var), "standarized variable"))
    p
    

    Or :

    p + scale_y_continuous("variable", sec.axis = sec_axis(~ scale(.), "standarized variable"))
    

    enter image description here