The contour function

Given a matrix, and optionally the grid of X-axis and Y-axis values, it is possible to create a contour plot in R with the contour function.

# Data
x <- -10:10
y <- -10:10
z <- sqrt(outer(x ^ 2, y ^ 2, "+"))

contour(x, y, z)

# You can also type, the following
# but the axes will be between 0 and 1
contour(z)

contour function in R

Number of levels

The nlevels argument controls the number of contour levels to be drawn. The default value is 10.

# Data
x <- -10:10
y <- -10:10
z <- sqrt(outer(x ^ 2, y ^ 2, "+"))

contour(x, y, z,
        nlevels = 20) 

R contour levels

Contour lines

Note that you can change the line width and line style of the contours with lwd and lty, respectively, as well as the size for contour labels with labcex, change the labels with labels or remove them setting drawlabels = FALSE.

# Data
x <- -10:10
y <- -10:10
z <- sqrt(outer(x ^ 2, y ^ 2, "+"))

contour(x, y, z,
        labcex = 1.2, labels = 1:10,
        lwd = 2, lty = 1) 

Customizing the contour lines of the R contour plot

Color palette

You can change the color of the contour lines with col, passing a color or a color palette, such in the example below, which draws contours for the volcano data set.

# Color palette
cols <- hcl.colors(10, "YlOrRd")

contour(volcano,
        col = cols)

Contour color palette

Overlay contour over a scatter plot

If you want to overlay contour lines over a scatter plot you can use the kde2d function from MASS to calculate the kernel density estimate of the variables as shown in the example below. Recall to set add = TRUE inside contour.

# install.packages("MASS")
library(MASS)

# Data
x <- rnorm(500)
y <- rnorm(500)
z <- kde2d(x, y, n = 50)

plot(x, y, pch = 19)
contour(z, lwd = 2 add = TRUE,
        col = hcl.colors(10, "Spectral"))

Scatter plot with contour levels plot in R

The filled.contour function

filled.contour function

A similar function to contour is filled.contour, which fills the areas between the contour lines. The function behaves almost the same as the function from the previous section.

filled.contour(volcano)

Number of levels of the filled contour

Number of levels

In this function you can also specify the number of levels with nlevels.

filled.contour(volcano,
               nlevels = 10)

filled.contour color palette

Color palette

The color palette can be set with color.palette or specifying a vector of colors with col.

filled.contour(volcano,
               color.palette = terrain.colors)

Filled contour with level contour lines in R

Filled contour with lines

The plot.axes function can be used to add a contour over the filled contour plot, as shown in the following example.

filled.contour(volcano, plot.axes = {
  axis(1)
  axis(2)
  contour(volcano, add = TRUE, lwd = 2)
  }
)

See also