# R/Contour Plots

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

# Contour Plots

Update: the ".filled.contour" function function in R 2.15 and beyond solves many of the problems described below.

Good contour plot

R has two built-in functions for contour plots, contour, and filled.contour. Examples of their use can be seen from the code below:

```x <- 1:50
y <- 1:70
z <- matrix(expand.grid(x,y)\$Var1^2 + expand.grid(x,y)\$Var2^2,50,70)

# plain
contour(x,y,z)

mylevels <- seq(0,7500,500)
contour(x,y,z,levels=mylevels,xaxs='i',yaxs='i')

# filled contours
filled.contour(x,y,z,color.palette=heat.colors)
filled.contour(x,y,z,col=grey(seq(0,1,length=length(mylevels))))
```

However, it can be frustrating to realize that the way filled.contour was implemented does not allow removing the key or overplotting with lines and labels. To realize this, add the lines below to the code above to create the bad figure above left.

```filled.contour(x,y,z,col=grey(seq(0,1,length=length(mylevels))))
```

A solution is to use the modified function, filled.contour2.R, as follows to create the better figure above right.

```# filled.contour function modified to not have key
filled.contour2(x,y,z,col=grey(seq(0.3,1,length=length(mylevels))))
# now we can successfully add lines and values
```

Better yet, Carey McGilliard and Bridget Ferris made further modifications to allow multiple filled contours per page and the addition of the legend on the side to makes figures like the one below. filled.contour3.R filled.legend.R

Good contour plot

An example of how these are combined with the aid of "plt" is found in the following file from Carey: Example 4 panel contour plot with one legend.R.

Here is a version of that same file, kindly modified by Steffen Uhlig to include more comments: Example 4-panel v1a.R. There are a variety of small differences, so it's probably worth looking at both files.