# Confidence bands with lattice and R

December 10, 2010
By

(This article was first published on Omnia sunt Communia! » R-english, and kindly contributed to R-bloggers)

If you use lattice with R, and you need to plot confidence limits in your graphic, then panel.smoother and panel.quantile from latticeExtra will help you with this task. These functions internally calculate the error bounds and use panel.polygon from lattice. If you need to plot your own confidence limits, then you have to define a panel function.

A suitable code is proposed here by Deepayan Sarkar, the developer of lattice:

```my.panel.bands <- function(x, y, upper, lower, fill, col,
subscripts, ..., font, fontface)
{
upper <- upper[subscripts]
lower <- lower[subscripts]
panel.polygon(c(x, rev(x)), c(upper, rev(lower)),
col = fill, border = FALSE,
...)
}
```

Then you can plot your data.frame, named “data” with:

```xyplot(formula, data=data, groups=groups,
upper = data\$high, lower = data\$low,
panel = function(x, y, ...){
panel.superpose(x, y, panel.groups = my.panel.bands, type='l', col='gray',...)
panel.xyplot(x, y, type='b', cex=0.6, lty=1,...)
}
)
```

where “data\$high” and “data\$low” are the error bounds of your data. You can also use the glayer function from latticeExtra if you do not feel confortable with panel functions inside xyplot.

In this article, I have used this tool to display confidence limits of the wavelet variance calculated with wmtsa, and I got the next figure:

R-bloggers.com 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...

Tags: , , ,