# [R] Plotting a fourth variable on a persp plot

Chelsea Edwards chelseaedwards92 at gmail.com
Fri Sep 4 14:20:32 CEST 2015

```Hi all,

I'm trying to plot colour as a fourth variable onto a persp plot to
highlight the multiple modes in my dataset.

A plot with 3 variables (frequency, time and depth) has been created using
the code below:

require(MASS)
require(graphics)
require(plot3D)
require(pdfCluster)

## density estimate and persp plot with 3 variables
f1 <- kde2d(Max_d, Bottom_t, n=124, lims=c(0, 90, 0, 140))
persp(f1, phi = 40, theta = 50, d = 5, col="lightblue", xlab="Maximum
diving depth, m", ylab="Bottom time, m", zlab="Number of dives")

# f1\$x represents depth - vector - length 124
# f1\$y represents bottom time (duration) - vector - length 124
# f1\$z is the frequency matrix - length 15375 (124 by 124 Matrix)

The colour variable has been produced as a vector (length 124) using a
cluster analysis
## Colour variable -  representing 3 modes within the data (1,2&3 in
g_class1)
test1 <- Penguins[,c(16, 11)]
test1a <- pdfCluster(test1, graphtype="delaunay", h=h.norm(test1),
hmult=1.2, options="Qt", kernel="gaussian", bwtype="fixed")
g_class1 <-groups(test1a, stage=5)
g1 <- data.frame(g_class1)
Penguins3 <- data.frame(c(Penguins, g1, f1))

## using persp3D and colvar to get colour plotted
persp3D(z=f1\$z, x=f1\$x, y=f1\$y, bty="bl2", axes=T,  facets=NA,
colvar=Penguins3\$g_class1, lighting=T, colkey=TRUE, xlab="Maximum depth",
ylab="Bottom_time", zlab="Number of dives",xlim=c(0,90), ylim=c(0,140),
ticktype="detailed", border=NA)

# error - as colvar is not equal in dimensions to matrix Z.

ggg1 <- matrix(Penguins3\$g_class1, nrow=124, ncol=124)
persp3D(z=f1\$z, x=f1\$x, y=f1\$y, bty="b2", axes=T, colvar=ggg1, colkey=TRUE,
xlab="Maximum depth", ylab="Bottom_time", zlab="Number of
dives",xlim=c(0,90), ylim=c(0,140), ticktype="detailed", border=NA)

# produces the chart but values are (obviously) wrong

I understand that my current colour variable is a vector when I actually
need a matrix, but I'm unsure how to get around this issue as the vector
length is 124 and the matrix I need would be 124X124.

Is there anyway to plot the colour as a variable over the perspective plot?