I want to plot a logistic regression curve of my data, but whenever I try to my plot produces multiple curves. Here's a picture of my last attempt:
last attempt
Here's the relevant code I am using:
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)
My professor uses the following code, but when I try to run it I get an error on the last line saying that the x and y lengths do not match:
# 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)
Any help would be appreciated.
Edit:
As requested, reproduceable code using the mtcars dataset:
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)
To plot the logistic regression curve in base R, we first fit the variables in a logistic regression model by using the glm() function. The glm() function is used to fit generalized linear models, specified by giving a symbolic description of the linear predictor.
To visualize the logistic regression fit, we first use the predict function to generate the model predictions about probability of survival as a function of age. Having generated the predicted probabilities of survival we can then add these prediction lines to our previous plot using geom_line .
However, the advantage of logistic regression is that any number of variables can be included, and if desired, all predictor variables may be categorical. In SPSS, you can graph a logistic regression through the "Options" menu of the "Binary logistic regression" window.
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)
Here's a function (based on Marc in the box's answer) that will take any logistic model fit using glm and create a plot of the logistic regression curve:
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With