Ggplot secondary y-axes showing z values ββusing sec_axis
ggplot2 now allows you to add 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 that additional axes are added using the sec_axis () function, for example
scale_y_continuous(sec.axis = sec_axis(~.+10))
creates a second y-axis 10 units higher than the first.
Z-scores can be generated in R using the scale () function . So I assumed I could do something like this to get the second y-axis displaying z-scores:
scale_y_continuous(sec.axis = sec_axis(scale(~.)))
However, this returns an "invalid first argument" error.
Does anyone have any ideas how to make this work?
source to share
You can use the z-score conversion 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"))
source to share