Creating Three-Dimensional Plots

R offers a number of functions to plot data in three dimensions such as persp() and wireframe(), which draw surfaces, and cloud(), which draws three-dimensional scatter plots. Here, we’ll look at a simple example that uses wireframe().

> library(lattice)
> a <- 1:10
> b <- 1:15
> eg <- expand.grid(x=a,y=b)
> eg$z <- eg$x^2 + eg$x * eg$y
> wireframe(z ˜ x+y, eg)

First, we load the lattice library. Then the call to expand.grid() creates a data frame, consisting of two columns named x and y, in all possible combinations of the values of the two inputs. Here, a and b had 10 and 15 values, respectively, so the resulting data frame will have 150 rows. (Note that the data frame that is input to wireframe() does not need to be created by expand.grid().)

We then added a third column, named z, as a function of the first two columns. Our call to wireframe() creates the graph. The arguments, given in regression model form, specify that z is to be graphed against x and y. Of course, z, x, and y refer to names of columns in eg. The result is shown in Figure 12-13.

Example of using wireframe()

Figure 12-13. Example of using wireframe()

All the points are connected as a surface (like connecting points by lines in two dimensions). In contrast, with cloud(), the points are isolated.

For wireframe(), the (x,y) pairs must form a rectangular grid, though not necessarily be evenly spaced.

The three-dimensional plotting functions have many different options. For instance, a nice one for wireframe() is shade=T, which makes the data easier to see. Many functions, some with elaborate options, and whole new graphics packages work at a higher (read “more convenient and powerful”) level of abstraction than R’s base graphics package. For more information, refer to the books cited in footnote 1 at the beginning of this chapter.