r - 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)
解决方案
我需要重新调整我的 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)
推荐阅读
- reactjs - 为什么 data-reactid 属性在某一天会在 DOM 中可见,而第二天不可见?
- python - 如何获取列表列表中的重复项数?
- python - 在 Pygame 中获取当前发出的音量
- java - Java 泛型参数
- javascript - 使用本地日期设置和获取 HTMLInputElement.valueAsDate 的正确方法是什么?
- android - 如何更改 TextInputLayout 小部件的提示字体大小?
- angular - 是否有任何现有的 Angular 代码查看器组件?
- angular - 占位符的材质角度更改颜色
- javascript - 如何在anime.js中沿运动路径获取点
- c# - 使用随机颜色实例化预制件