geom_smooth 自定义线性模型

geom_smooth custom linear model

在查看 this 问题时,我无法为 geom_smooth 指定自定义线性模型。我的代码如下:

example.label <- c("A","A","A","A","A","B","B","B","B","B")
example.value <- c(5, 4, 4, 5, 3, 8, 9, 11, 10, 9)
example.age <- c(30, 40, 50, 60, 70, 30, 40, 50, 60, 70)
example.score <- c(90,95,89,91,85,83,88,94,83,90)
example.data <- data.frame(example.label, example.value,example.age,example.score)

p = ggplot(example.data, aes(x=example.age,
                         y=example.value,color=example.label)) +
  geom_point()
  #geom_smooth(method = lm)

cf = function(dt){
  lm(example.value ~example.age+example.score, data = dt)
}

cf(example.data)

p_smooth <- by(example.data, example.data$example.label, 
               function(x) geom_smooth(data=x, method = lm, formula = cf(x)))

p + p_smooth 

我收到这个 error/warning:

Warning messages:
1: Computation failed in `stat_smooth()`:
object 'weight' not found 
2: Computation failed in `stat_smooth()`:
object 'weight' not found 

为什么我会收到这个?为 geom_smooth 指定自定义模型的正确方法是什么?谢谢。

具有两个连续预测变量和连续结果的回归模型的回归函数存在于 3D space(两个用于预测变量,一个用于结果),而 ggplot 图是 2D space(x 轴上的一个连续预测变量和 y 轴上的结果)。这就是为什么你不能用 geom_smooth.

绘制两个连续预测变量的函数的根本原因

一个 "workaround" 是选择一个连续预测变量的几个特定值,然后为第一个变量的每个选定值在 x 轴上为另一个连续预测变量绘制一条线.

下面是 mtcars 数据框的示例。下面的回归模型使用 wthp 预测 mpg。然后,我们针对 hp 的各种值绘制 mpgwt 的预测。我们创建一个预测数据框,然后使用 geom_line 进行绘图。图中的每条线代表 mpgwt 的不同值 hp 的回归预测。当然,您也可以颠倒 wthp 的角色。

library(ggplot)
theme_set(theme_classic())

d = mtcars
m2 = lm(mpg ~ wt + hp, data=d)

pred.data = expand.grid(wt = seq(min(d$wt), max(d$wt), length=20),
                        hp = quantile(d$hp))
pred.data$mpg = predict(m2, newdata=pred.data)

ggplot(pred.data, aes(wt, mpg, colour=factor(hp))) +
  geom_line() +
  labs(colour="HP Quantiles")

另一种选择是使用颜色渐变来表示 mpg(结果)并在 x 和 y 轴上绘制 wthp

pred.data = expand.grid(wt = seq(min(d$wt), max(d$wt), length=100),
                        hp = seq(min(d$hp), max(d$hp), length=100))
pred.data$mpg = predict(m2, newdata=pred.data)

ggplot(pred.data, aes(wt, hp, z=mpg, fill=mpg)) +
  geom_tile() +
  scale_fill_gradient2(low="red", mid="yellow", high="blue", midpoint=median(pred.data$mpg))