# Logistic Regression plot in R

Logistic Regression plot in R, you will learn how to plot a Logistic Regression Curve in the R programming language in this tutorial.

A supervised classification algorithm, logistic regression is. This aids in the creation of a distinguishing curve that distinguishes between two classes of variables.

In R, plotting the curve of a fitted logistic regression model is a common task.

Fortunately, this is a simple task, and this tutorial will show you how to accomplish it in both R and ggplot2.

## Approach1: Base R, create a Logistic Regression Curve

The following code demonstrates how to construct a logistic regression model in R using variables from the built-in mtcars dataset, followed by plotting the logistic regression curve:

Model of the logistic regression fit

Model1<- glm(vs ~ hp, data=mtcars, family=binomial) Model1

Call: glm(formula = vs ~ hp, family = binomial, data = mtcars) Coefficients: (Intercept) hp 8.37802 -0.06856 Degrees of Freedom: 31 Total (i.e. Null); 30 Residual Null Deviance: 43.86 Residual Deviance: 16.84 AIC: 20.84

create a new data frame with the predictor variable

new<- data.frame(hp=seq(min(mtcars$hp), max(mtcars$hp),len=500)) head(new)

hp 1 52.00000 2 52.56713 3 53.13427 4 53.70140 5 54.26854 6 54.83567

To anticipate the values of vs, utilise a fitted model.

new$vs = predict(Model1, new, type="response") head(new)

hp vs 1 52.00000 0.9919409 2 52.56713 0.9916241 3 53.13427 0.9912949 4 53.70140 0.9909529 5 54.26854 0.9905975 6 54.83567 0.9902284

Now we can plot the logistic regression curve

plot(vs ~ hp, data=mtcars, col="steelblue") lines(vs ~ hp, newdata, lwd=2)

The x-axis shows the values of the predictor variable hp, while the y-axis shows the responder variable am’s projected probability.

Higher values of the predictor variable hp are clearly connected with lower probabilities of the responder variable vs equaling 1.

## Approach2: Plot a Logistic Regression Curve in ggplot2

Using the data visualization library ggplot2, the following code explains how to fit the same logistic regression model and plot the logistic regression curve:

library(ggplot2)

plot logistic regression curve

ggplot(mtcars, aes(x=hp, y=vs)) + geom_point(alpha=.5) + stat_smooth(method="glm", se=FALSE, method.args = list(family=binomial))

This is the same curve that was created in the previous example using base R.

Feel free to change the curve’s style as well. We could, for example, make the curve into a red dashed line.

library(ggplot2)

Let’s plot the logistic regression curve

ggplot(mtcars, aes(x=hp, y=vs)) + geom_point(alpha=.5) + stat_smooth(method="glm", se=FALSE, method.args = list(family=binomial), col="pink", lty=2)