The end of the line for error bars in R

November 5, 2013

(This article was first published on John Baumgartner's Research » R, and kindly contributed to R-bloggers)

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.
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)
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.

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. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)