【问题标题】:How to plot lm slope modeled using poly()?如何绘制使用 poly() 建模的 lm 斜率?
【发布时间】:2019-04-09 23:29:33
【问题描述】:

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

【问题讨论】:

  • 我通常通过predict() 获取预测值来解决此类问题。它本质上是一个方便的功能,可以做(我认为)你想做的事情。

标签: r plot poly


【解决方案1】:

其实poly可以直接在lm()的公式中使用。

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


如果要删除点:删除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))

【讨论】:

  • 非常感谢!在我的真实数据集中,我有数百万行,不容易绘制(我在等待 30 分钟后停止了)。因此,我的目标只是在没有数据的情况下绘制斜率。你知道这样做的方法吗?再次感谢您!
  • 如果您不想要积分,只需在我的代码中删除geom_point。每个geom_ 只是一层,因此您可以根据需要轻松排除它。
  • 如果问题是多点问题,还有一个透明度选项。 alpha 01 之间的参数就是这样做的。对于积分,在这种情况下,可以应用geom_point(alpha = .5)或其他一些不中断线路的小数字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-11
  • 1970-01-01
  • 1970-01-01
  • 2016-08-12
  • 1970-01-01
  • 1970-01-01
  • 2020-03-05
相关资源
最近更新 更多