r - 如何绘制使用 poly() 建模的 lm 斜率?

标签 r plot poly

我需要绘制 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

    lm() 中的
  1. y ~ poly(x, 3) 可能就是您想要的。
  2. 对于绘图,我将使用具有 geom_smooth() 函数的 ggplot2 包。它可以绘制拟合曲线。您应该指定
    • 方法 = "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

enter image description here


如果要删除点:erase geom_point()

df %>%
  ggplot() +
  aes(x, y) +
  geom_smooth(method = "lm", formula = y ~ poly(x, 3))

enter image description here


透明度解决方案:控制alpha小于1

df %>%
  ggplot() +
  aes(x, y) +
  geom_point(alpha = .3) +
  geom_smooth(method = "lm", formula = y ~ poly(x, 3))

enter image description here

关于r - 如何绘制使用 poly() 建模的 lm 斜率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53174150/

相关文章:

r - 通过(非统一)名称连接两个数据集

python - 创建两个分类变量的热图

python - 散点图覆盖的 matplotlib 轴刻度标签(使用脊柱)

r - 在小标题中查看超过10行时遇到问题

r - R中的Boruta箱形图

R:data.table .动态聚合列日期列

r - 在 RStudio 中循环期间绘图

java - 在多项式方程中合并相似项

r - 在计算逐步多项式回归之前如何消除p值> 0.7的变量?

r - 在数据框列上使用 Poly