geom_smooth custom linear model

AK8*_*K88 6 r ggplot2 lm

While looking at this issue, I couldn't specify a custom linear model to geom_smooth. My code is as follows:

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 
Run Code Online (Sandbox Code Playgroud)

I am getting this error/warning:

Warning messages:
1: Computation failed in `stat_smooth()`:
object 'weight' not found 
2: Computation failed in `stat_smooth()`:
object 'weight' not found 
Run Code Online (Sandbox Code Playgroud)

Why am I getting this? And what is the proper method of specifying a custom model to geom_smooth. Thanks.

eip*_*i10 4

具有两个连续预测变量和一个连续结果的回归模型的回归函数位于 3D 空间中(两个用于预测变量,一个用于结果),而 ggplot 图是一个 2D 空间(x 轴上有一个连续预测变量)以及 y 轴上的结果)。这就是为什么您无法使用 绘制两个连续预测变量的函数的根本原因geom_smooth

一种“解决方法”是选择一个连续预测变量的几个特定值,然后为第一个变量的每个选定值在 x 轴上绘制另一个连续预测变量的线。

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

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")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

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)) 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述