ggplot2 allows adding secondary y-axis if one-to-one transformation of primary axis.
for graph, plot original units on left y-axis , z-scores on right y-axis, having trouble working out how in practice.
the documentation suggests secondary axes added using sec_axis() function e.g.,
scale_y_continuous(sec.axis = sec_axis(~.+10))
creates second y-axis 10 units higher first.
z-scores can created in r using scale() function. assumed second y-axis displaying z-scores:
scale_y_continuous(sec.axis = sec_axis(scale(~.)))
however, returns "invalid first argument" error.
does have ideas how make work?
you use z-score transformation formula. 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"))
Comments
Post a Comment