Gradient Color 3D Surface Plots using the R Language

The R language is often used by data scientists. The language has strong numerical and statistical functions. Here’s an example which shows how to make a 3D surface plot of Rastigin’s function (a standard benchmark used to evaluate numerical optimization algorithms) with a color gradient.


The R code is:

x<-seq(-5.12, 5.12, length=100)
y<-seq(-5.12, 5.12, length=100)
f<-function(x,y) { 20+(x^2-10*cos(2*3.14*x))+
     (y^2-10*cos(2*3.14*y)) }
jet.colors <-  colorRampPalette(c("midnightblue","blue",
     "cyan","green", "yellow","orange","red", "darkred"))

The first four commands set values of Rastrigin’s function in a matrix z. The next two statements set up the number of row and columns in the z matrix. The jet.colors object holds the range of colors to use in the color gradient. You can use any two or more colors here.

Variable nbcol (64) is the number of different colors to use. The zfacet equation calculates the color for each square on the plot. You can think of it as a magic equation. The cut function used with object facetcol (“facet color”) divides its arguments into intervals.

The persp function generates the 3D plot. This example can be used as a template to generate a 3D surface plot of other functions — just change the definition of f (and the ranges for x and y).

This entry was posted in Machine Learning. Bookmark the permalink.