我需要绘制 x 和 y 之间的关系,其中 x 的多项式预测 y。这是使用 poly() 函数完成的,以确保多项式是正交的。
如何同时考虑线性项、二次项和三次项来绘制这种关系?问题是不同项的系数没有像 x 那样缩放。
我在下面提供了一些示例代码。我尝试将每个多项式的对比度值重新分配给 x。
该解决方案给出了不可能的预测值。
预先感谢您的帮助!
最美好的祝愿, 埃里克
这里是一个示例代码:
x = sample(0:6,100,replace = TRUE)
y = (x*0.2) + (x^2*.05) + (x^3*0.001)
y = y + rnorm(100)
x = poly(x,3)
m = lm(y~x)
TAB = summary(m)$coefficients
### Reassigning the corresponding contrast values to each polynomial of x:
eq = function(x,TAB,start) {
#argument 'start' is used to determine the position of the linear coefficient, quadratic and cubic follow
pols = poly(x,3)
x1=pols[,1]; x2=pols[,2]; x3=pols[,3]
TAB[1,1] + x1[x]*TAB[start,1] + x2[x] * TAB[start+1,1] + x3[x] * TAB[start+2,1]
}
plot(eq(0:7,TAB,2))
最佳答案
实际上,您可以直接在 lm()
的公式中使用 poly
。
y ~ poly(x, 3)
可能就是您想要的。- 对于绘图,我将使用具有
geom_smooth()
函数的ggplot2
包。它可以绘制拟合曲线。您应该指定方法 = "lm"
参数- 和公式
lm()
中的library(tidyverse)
x <- sample(0:6,100,replace = TRUE)
y <- (x*0.2) + (x^2*.05) + (x^3*0.001)
eps <- rnorm(100)
(df <- data_frame(y = y + eps, x = x))
#> # A tibble: 100 x 2
#> y x
#> <dbl> <int>
#> 1 3.34 4
#> 2 1.23 5
#> 3 1.38 3
#> 4 -0.115 2
#> 5 1.94 5
#> 6 3.87 6
#> 7 -0.707 3
#> 8 0.954 3
#> 9 1.19 3
#> 10 -1.34 0
#> # ... with 90 more rows
使用您的模拟数据集,
df %>%
ggplot() + # this should be declared at first with the data set
aes(x, y) + # aesthetic
geom_point() + # data points
geom_smooth(method = "lm", formula = y ~ poly(x, 3)) # lm fit
如果要删除点:erase geom_point()
df %>%
ggplot() +
aes(x, y) +
geom_smooth(method = "lm", formula = y ~ poly(x, 3))
透明度解决方案:控制alpha
小于1
df %>%
ggplot() +
aes(x, y) +
geom_point(alpha = .3) +
geom_smooth(method = "lm", formula = y ~ poly(x, 3))
关于r - 如何绘制使用 poly() 建模的 lm 斜率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53174150/