【问题标题】:Plot logistic regression curve in R在 R 中绘制逻辑回归曲线
【发布时间】:2016-08-09 17:10:05
【问题描述】:

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

last attempt

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

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)

我的教授使用以下代码,但是当我尝试运行它时,我在最后一行收到错误,提示 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)

任何帮助将不胜感激。

编辑:

根据要求,使用 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)

【问题讨论】:

  • 所以有lots of questions on plotting logistic regression curves。他们中的任何一个有帮助吗?
  • 请参阅提供的链接 eipi,或使您的示例可重现。模拟一些适合您已经提供的代码的数据。
  • 我确实尝试过先搜索 SO,但大多数问题涉及的内容超出了我的想象,或者没有解决我遇到的问题。我发布了一些使用内置 mtcars 数据集的代码,以便可以重现问题。
  • newdata=hr ?你有newdata=dat

标签: r plot statistics regression


【解决方案1】:
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)

【讨论】:

  • 你能告诉我第二行和第三行的目的是什么吗? newdat 的作用是什么?
  • newdatobject 用于预测。这包含比原始数据集更精细的可能hpvalues 分辨率,并且它们被排序以便于绘制。当您创建 hr 时,您正在正确执行此操作,但是您没有在预测步骤中使用它 - 您使用了 newdata=dat
【解决方案2】:

这是一个函数(基于方框答案中的 Marc),它将使用 glm 拟合任何逻辑模型并创建逻辑回归曲线图:

plot_logistic_curve = function(log_mod){
  mod_frame = model.frame(log_mod)
  var_names = names(mod_frame)
  newdat = setNames(data.frame(seq(min(mod_frame[[2]]), max(mod_frame[[2]]), len=100)), var_names[2])
  newdat[var_names[1]] = predict(log_mod, newdata = newdat, type="response")
  plot(mod_frame[[1]] ~ mod_frame[[2]], col = "red4", xlab = var_names[[2]], ylab = var_names[[1]])
  lines(newdat[[var_names[2]]], newdat[[var_names[1]]], col = "green4", lwd = 2)
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-13
    • 2014-04-22
    • 2015-02-19
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 2021-11-23
    • 2013-08-29
    相关资源
    最近更新 更多