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)) }
z<-outer(x,y,f)
nrz<-nrow(z)
ncz<-ncol(z)
jet.colors <- colorRampPalette(c("midnightblue","blue",
"cyan","green", "yellow","orange","red", "darkred"))
nbcol<-64
color<-jet.colors(nbcol)
zfacet<-z[-1,-1]+z[-1,-ncz]+z[-nrz,-1]+z[-nrz,-ncz]
facetcol<-cut(zfacet,nbcol)
persp(x,y,z,col=color[facetcol],phi=20,theta=-60,
ticktype="detailed",d=5,r=1,shade=0.1,expand=0.6)

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).

### Like this:

Like Loading...

*Related*