在查看这个问题时,我无法为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
我遇到了这个错误/警告:
Warning messages:
1: Computation failed in `stat_smooth()`:
object 'weight' not found
2: Computation failed in `stat_smooth()`:
object 'weight' not found
我为什么会得到这个?如何正确指定自定义模型给 geom_smooth
方法。谢谢。
geom_smooth
的模型公式只能以y ~ f(x)
的形式表示(例如,y ~ x
是默认的,或者y ~ poly(x, 2)
、y ~ bs(x, df=4)
等)。公式只能包括 x 和 y,它们将代表您传递给aes
作为绘图 x 和 y 美学的任何数据列。如果您想绘制多元回归的结果,您可以构建一个数据框传递给predict
,然后使用例如geom_line
绘制输出。 - eipi10geom_smooth
做的就是绘制包括y和x美学变量以及任何分类美学变量(例如颜色、形状)在内的回归。例如,在你的情况下,你可以做p + geom_smooth(method=lm, formula=y ~ poly(x, 2))
或者p + geom_smooth(method=lm, formula=y ~ splines::bs(x, df=4))
(尽管你需要更多的数据来理解后者)。这将为每个example.label
级别提供单独的回归线。 - eipi10mtcars
数据框,这里是mpg
与wt
的回归线,但按vs
和am
的级别进行分类:ggplot(mtcars,aes(wt,mpg,colour = interaction(vs,am,sep =“_”)))+ geom_point()+ geom_smooth(se = FALSE,method =“lm”)
。 - eipi10