绘制R中的逻辑回归曲线

caf*_*lar 8 statistics plot regression r

我想绘制我的数据的逻辑回归曲线,但每当我尝试我的情节时会产生多条曲线.这是我上一次尝试的照片:

最后一次尝试

这是我正在使用的相关代码:

fit = glm(output ~ maxhr, data=heart, family=binomial)
predicted = predict(fit, newdata=heart, type="response")

 plot(output~maxhr, data=heart, col="red4")
 lines(heart$maxhr, predicted, col="green4", lwd=2)
Run Code Online (Sandbox Code Playgroud)

我的教授使用以下代码,但是当我尝试运行它时,我在最后一行得到一个错误,说x和y长度不匹配:

# fit logistic regression model
fit = glm(output ~ maxhr, data=heart, family=binomial)
# plot the result
hr = data.frame(maxhr=seq(80,200,10))
probs = predict(fit, newdata=dat, type="response")
plot(output ~ maxhr, data=heart, col="red4", xlab ="max HR", ylab="P(heart disease)")
lines(hr$maxhr, probs, col="green4", lwd=2)
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激.

编辑:

根据要求,使用mtcars数据集的可重现代码:

fit = glm(vs ~ hp, data=mtcars, family=binomial)
predicted= predict(fit, newdata=mtcars, type="response")
plot(vs~hp, data=mtcars, col="red4")
lines(mtcars$hp, predicted, col="green4", lwd=2)
Run Code Online (Sandbox Code Playgroud)

Mar*_*box 13

fit = glm(vs ~ hp, data=mtcars, family=binomial)
newdat <- data.frame(hp=seq(min(mtcars$hp), max(mtcars$hp),len=100))
newdat$vs = predict(fit, newdata=newdat, type="response")
plot(vs~hp, data=mtcars, col="red4")
lines(vs ~ hp, newdat, col="green4", lwd=2)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • “ newdat”对象用于预测。与原始数据集相比,它包含可能的“ hp”值更好的分辨率,并且对它们进行了排序以便于绘制。创建hr时,您可以正确执行此操作,但是随后在预测步骤中未使用它-您使用的是newdata = dat。 (2认同)