R Line Plot With Error Bands
We want to create this plot using only base R graphics. You can do it using a default plot plus a call to segments
.
The Data
Here’s the data on elasticities by industry:
elasticity <- c(1.4, 0.8, 3.9, 5.6, 2.4)
And the corresponding standard errors:
stderr <- c(1.1, 0.2, 1.0, 2.1, 1.6)
The lower and upper values of the 95% confidence bands are:
lower <- elasticity - 1.96*std.err
upper <- elasticity + 1.96*std.err
In many cases, it’s more readable to plot the sorted data. Get the index of the sorted values of elasticity:
index <- order(elasticity)
Make the Plot
Now make the plot (with an explanation for each argument following:
plot(x[index], 5:1, xlim=c(min(lower)-0.5, max(upper)+0.5), yaxt="n", ylab="", xlab="Elasticity")
x[index]
: Plot the observations in sorted order rather than the raw ordering.5:1
: There are five observations. We put them aty=5
,y=4
, etc.xlim=c(min(lower)-0.5, max(upper)+0.5)
: We want to ensure the x range of the graph is wide enough to cover all elasticities and their error bars.yaxt="n"
: Omit the y-axis so you can add your own labels for the values on the y-axis.ylab=""
: Don’t label the y-axis.xlab="Elasticity"
: Label for the x-axis.
Add y-axis Labels
names <- c("Farm", "Finance", "Mining", "Services", "Retail")
axis(2, at=5:1, labels=names, las=2)
This is standard use of the axis
function. The arguments are:
2
: Tells it to put it on the y-axis.at
: Tells it to put the labels at y values that match what we used in the call toplot
.labels=names
: The labels to put on the y-axis.las=2
: Make the labels perpendicular to the y-axis.
Add the Error Bars
segments(lower[index], 5:1, x1=upper[index])
lower[index]
: The x coordinate of the starting values of each error band. The[index]
matches the lower bound of the confidence interval with the correct elasticity.5:1
: The y value for the error bar; has to match the y value of the elasticity in theplot
function call.x1=upper[index]
: Having an error band means we need to specify the ending value of the band. Since our error bands are horizontal, we only need to specify the x coordinate of the ending value of the error band.