首页 > 解决方案 > R 绘制多项式回归线

问题描述

我尝试绘制多项式回归线,但绘制的线没有意义。我使用包数据集中的 iris 数据集。这是我的代码:

library(datasets)
data2 <- iris[iris$Species != "setosa", ]
x<- data2$Sepal.Length
y <- data2$Species
fit <- lm(y ~ poly(x, 3))   ## polynomial of degree 3
plot(x, y)  ## scatter plot (colour: black)

x0 <- seq(min(x), max(x), length = 20)  ## prediction grid
y0 <- predict.lm(fit, newdata = list(x = x0))  ## predicted values
lines(x0, y0, col = 2) 

标签: rplotregression

解决方案


我需要重新调整我的 y 值。此代码有效:

library(datasets)
data2 <- iris[iris$Species != "setosa", ]
data2["Species"] <- as.numeric(unlist(data2["Species"]))
x<- data2$Sepal.Length
y <- data2$Species
y <- rescale(data2$Species, to = c(0, 1), from = range(x, na.rm = TRUE, finite = TRUE))
fit <- lm(y ~ poly(x, 3))   ## polynomial of degree 3
plot(x, y)  ## scatter plot (colour: black)

x0 <- seq(min(x), max(x), length = 20)  ## prediction grid
y0 <- predict.lm(fit, newdata = list(x = x0))  ## predicted values
lines(x0, y0, col = 2) 

推荐阅读