Every so often I want to plot some data with pretty upper and lower error bounds, such as temperature data through time, perhaps with the maximum and minimum temperature range or standard error bounds for averaged data. The polygon( ) function can make those sorts of pretty plots. However, I’ll often have chunks of missing data for periods of time, so I have to break up the polygons that go with the plotted data. I could swear I wrote a function to do this several months ago, but it’s lost in a pile of other scripts, so I re-wrote a function to accomplish the task. The plot above shows the kind of thing I’m talking about. I might have a series of times, or dates, or just random x data, and associated y values (a mean, and upper and lower bounds around the mean). But somewhere in the data set the y-values are missing. The goal is to simplify the process of generating the x-y pair values needed for polygon( ) to plot the error values, and automatically deal with any breaks in the data set. The R script to generate the function polylims( ) is hosted on GitHub. The function should handle datasets with any number of missing chunks, but it will also work equally well on datasets without missing points. John McKinlay pointed me to the rle( ) function shortly after I originally posted this, and it helps shrink the amount of code considerably. The modified code is shown below: Run that once, and it creates a function called polylims that you can use in your R session. Below is an example of how I use it. We’ll start by generating some junk data consisting of a time series of y-values, with upper and lower error bounds. Assemble those into a data frame, and lose some of the data in the middle of the series. After doing that, I’ll call the polylims( ) function, passing it the x data and the upper/lower error bounds. The original ‘y’ data aren’t needed here, just the upper/lower bounds. The output object ‘polys’ is a list of data frames, each containing a column x and column y, which hold the x-y pairs needed to plot each polygon. Since there is a break in the example data, ‘polys’ contains two such data frames. Continue by plotting the data. The for loop in the middle steps through each of the items in the ‘polys’ list, extracts the x&y values, and uses them to draw the polygon. After drawing the polygon, it’s usually a good idea to replot the original line over top, since the polygon may obscure it. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Source.