Site icon R-bloggers

The end of the line for error bars in R

[This article was first published on John Baumgartner's Research » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

When plotting in R, I often use the segments function to add lines representing confidence intervals. This is a very simple way to plot lines connecting pairs of x,y coordinates.

Recently I discovered that by default, segments are styled with rounded line caps, which add to their length. This means, of course, that confidence intervals are slightly wider than intended.

R provides three styles of line ending – round, butt and square – which can be specified by the lend argument. The figure here shows the outcome of using each line ending, with vertical lines indicating actual end-points of segments. Both round and square line ends overshoot these points, while butt ends represent them correctly.

plot.new()
par(mar=c(1, 4, 1, 1))
plot.window(xlim=c(0, 1), ylim=c(0.5, 3.5))
axis(2, 1:3, c('round', 'butt', 'square'), las=1)
box(lwd=2)
segments(0.1, 1, 0.9, 1, lwd=20, lend='round')
segments(0.1, 2, 0.9, 2, lwd=20, lend='butt')
segments(0.1, 3, 0.9, 3, lwd=20, lend='square')
abline(v=c(0.1, 0.9))

Line end styles applied to segments plotted in R. Only ‘butt’ accurately represents end points.

The effect is slight, and is emphasized when line width is large. Regardless, it’s a good idea to routinely add lend='butt' (or lend=2) to your segments function calls.

A secondary benefit is that lines will appear crisper than when plotted with the default round caps.


Filed under: R Tagged: error bars, plotting, R, rstats, segments, tips&tricks

To leave a comment for the author, please follow the link and comment on their blog: John Baumgartner's Research » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.