Can you reverse scaling and centering in the axes of a ggplot2 plot?

Viewed 148

I want to scale the predictor variable of a regression model but I then want to plot the original values on the x-axis for intelligibility using ggplot2. I have attempted to do this using scale_x_continuous().

library('tidyverse')
x <- rnorm(100, 10, 1.5)
Zx <- scale(x)
Zy <- .8*Zx + rnorm(100, 0, sqrt(1 - (.8^2)))
df <- tibble(Zx = Zx, y = Zy)


SD_scale <- attr(df$Zx, "scaled:scale")
center   <- attr(df$Zx, "scaled:center")

unscale_trans <- function(x){
  scales::trans_new(
    "unscale",
    function(x) center + x * SD_scale,
    function(x) scale(x) )
}

df %>%
  ggplot(aes(x=Zx,y=y)) + geom_point()  + 
  geom_smooth(method = "lm") +
  scale_x_continuous(trans="unscale")

This throws the following warnings:

1: In c(-1, 1) * (width * mul + add) : Recycling array of length 1 in vector-array arithmetic is deprecated. Use c() or as.vector() instead.

2: In c(-1, 1) * (width * mul + add) : Recycling array of length 1 in vector-array arithmetic is deprecated. Use c() or as.vector() instead.

And results in oddly scaled labels.

Scaled x predictor

Is there a means of satisfactorily 'unscaling' the axis?

Thank you in advance for your help,

John

0 Answers
Related