【发布时间】:2017-11-30 01:29:32
【问题描述】:
查看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
我收到此错误/警告:
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绘制输出。 -
您是否值得尝试重塑数据,然后为
x和subset函数使用单列? -
这不是真正的重塑问题。你真正可以用
geom_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的每个级别提供单独的回归线。 -
例如,对于
mtcars数据框,这里是mpg与wt的回归线,但按vs和am的级别分类:ggplot(mtcars, aes(wt, mpg, colour=interaction(vs, am, sep="_"))) + geom_point() + geom_smooth(se=FALSE, method="lm")。 -
我明白了,谢谢。看起来没有解决方法...
标签: r ggplot2 regression lm