Sunday, October 05, 2008
I mentioned in class that I had written a cleaner function in R to plot error bars. It is below along with some simulated data to show how to use it.
-Yair
###################################################################################################
# basic function to plot a model's coefficients and error bars
# by Yair Ghitza (yg2173@columbia.edu)
# based on Jonathan Kastellec and Eduardo Leoni's code (www.tables2graphs.com)
library(arm)
plot.errorbars <- function(model, ...)
{
v_coef <- coef(model)
v_se <- se.coef(model)
v_low <- v_coef-qnorm(.975)*v_se
v_high <- v_coef+qnorm(.975)*v_se
v_labels <- labels(coef(model))
v_yaxis <- c(length(v_coef):1)
v_xlimits <- c(floor(min(v_low)), ceiling(max(v_high)))
par(mar=c(3, 15, 4, 2)) # make room for the labels on the left
plot(v_coef, v_yaxis, pch=19, axes=F, xlab="", ylab="", xlim=v_xlimits, ...)
segments(v_coef-qnorm(.975)*v_se, v_yaxis, v_coef+qnorm(.975)*v_se, v_yaxis, lwd=1)
segments(v_coef-qnorm(.750)*v_se, v_yaxis, v_coef+qnorm(.750)*v_se, v_yaxis, lwd=2)
axis(1, at=seq(v_xlimits[1], las=1, v_xlimits[2],
by=ifelse(v_xlimits[2] - v_xlimits[1] > 10, ceiling((v_xlimits[2] - v_xlimits[1])/10), 1)))
axis(2, at=v_yaxis, label=v_labels, las=1, tick=F)
segments(0, -1, 0, length(v_coef)+1, lty=2)
par(mar=c(5, 4, 4, 2) + 0.1) # reset margins
}
# simulate fake data and create a model
n <- 1000
x1 <- rnorm(n)
x2 <- rnorm(n)
x3 <- rnorm(n)
x4 <- rnorm(n)
x5 <- rnorm(n)
error <- rnorm(n,0,15) # large error term so we get visible standard errors
y <- 2 - 1*x1 - 1.5*x2 + 1*x3 - 0.01*x4 + 1.5*x5 + error
M1 <- lm(y ~ x1 + x2 + x3 + x4 + x5)
summary(M1)
# plot it (note the "main=..." argument is optional to create the title")
plot.errorbars(M1, main=paste("Linear model 1,\nN=", length(M1$fitted.values), sep=""))