首页 > 解决方案 > 您可以在 ggplot2 绘图的轴上反向缩放和居中吗?

问题描述

我想缩放回归模型的预测变量,但我想使用 ggplot2 在 x 轴上绘制原始值以获得可理解性。我尝试使用 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")

这会引发以下警告:

1:在 c(-1, 1) * (width * mul + add) 中:不推荐在向量数组算术中回收长度为 1 的数组。请改用 c() 或 as.vector() 。

2:在 c(-1, 1) * (width * mul + add) 中:不推荐在向量数组算术中回收长度为 1 的数组。请改用 c() 或 as.vector() 。

并导致奇怪的缩放标签。

缩放 x 预测器

是否有令人满意的“缩放”轴的方法?

预先感谢您的帮助,

约翰

标签: rggplot2regression

解决方案


推荐阅读