R Resources‎ > ‎

Plotting logistic regression in R

This set of codes will produce plots for logistic regression. Text that follows # sign is ignored by R when running commands, so you can just copy-and-paste these straight into your R console or R document.

#First, we'll create a fake dataset of 20 individuals of different body sizes:
bodysize=rnorm(20,30,2) # generates 20 values, with mean of 30 & s.d.=2
bodysize=sort(bodysize) # sorts these values in ascending order.
survive=c(0,0,0,0,0,1,0,1,0,0,1,1,0,1,1,1,0,1,1,1) # assign 'survival' to these 20 individuals non-randomly... most mortality occurs at smaller body size
dat=as.data.frame(cbind(bodysize,survive)) # saves dataframe with two columns: body size & survival
dat # just shows you what your dataset looks like. It will look something like this:


#   bodysize survive
#1  25.63320       0
#2  26.46724       0
#3  27.05107       0
#4  27.78609       0
#5  27.88550       0
#6  28.21167       1
#7  28.26452       0
#8  28.33589       1
#9  28.41717       0
#10 28.70792       0
#11 29.20096       1
#12 29.59447       1
#13 29.65526       0
#14 30.13143       1
#15 30.54080       1
#16 30.95309       1
#17 31.04085       0
#18 31.55717       1
#19 32.13806       1
#20 32.95669       1
-----
Plotting method 1: manual plotting with actual logistic regression

quartz(title="bodysize vs. survival") # creates a quartz window with title

plot(bodysize,survive,xlab="Body size",ylab="Probability of survival") # plot with body size on x-axis and survival (0 or 1) on y-axis
g=glm(survive~bodysize,family=binomial,dat) # run a logistic regression model (in this case, generalized linear model with logit link). see ?glm

curve(predict(g,data.frame(bodysize=x),type="resp"),add=TRUE) # draws a curve based on prediction from logistic regression model

points(bodysize,fitted(g),pch=20) # optional: you could skip this draws an invisible set of points of body size survival based on a 'fit' to glm model. pch= changes type of dots.



### or ####

library(popbio)
logi.hist.plot(bodysize,survive,boxp=FALSE,type="hist",col="gray")


# This creates a histogram + curve combo recommended by Smart et al. 2004

####

Check out some other plots in R:

Comments