Problem of coloring 3D scatterplot using "plot3D"

233 views Asked by At

I am trying to create a 3D scatter plot using plot3D package. Unfortunately I have a trouble in assigning color to each points.

For example, when I try to draw 8 points on the plot and I want to assign "black" to first 4 points and "red" to last 4 points respectively, I have written the following script (in this script, I employed 8 sample from the sample dataset iris and tried to assign Sepal.Length, Petal.Length, Sepal.Width to X, Y, Z axis, respectively);

data(iris)
sep.l <- iris[1:8,]$Sepal.Length
pet.l <- iris[1:8,]$Petal.Length
sep.w <- iris[1:8,]$Sepal.Width


library(plot3D)
scatter3D(x=sep.l, y=pet.l, z=sep.w,
pch =19,
bty = "b2",
colkey= FALSE,
col=c(rep("black", 4), rep("red", 4)))

In this case, strangely enough, 6 points were colored black and 2 points were colored red, respectively. I am completely at a loss why this happens.

I would appreciate so much if you kindly let me know how to solve this problem. Thank you very much in advance!

1

There are 1 answers

0
Ben On

The reason you see 6 black and 2 red, is that colvar is missing from your scatter3D call to be used with col in coloring.

In your example, the color is based on your z-axis. To demonstrate, we can add back the colkey, add ticktype to see axis information, and rotate a bit to show the red color is applied for values over 3.45 in sep.w (z-axis), which only includes 2 values from your data (3.6 and 3.9).

data(iris)

sep.l <- iris[1:8,]$Sepal.Length
pet.l <- iris[1:8,]$Petal.Length
sep.w <- iris[1:8,]$Sepal.Width

library(plot3D)

scatter3D(x = sep.l, y = pet.l, z = sep.w,
          pch = 19,
          bty = "b2",
          colkey = TRUE,
          phi = 15,
          theta = 30,
          col=c(rep("black", 4), rep("red", 4)),
          ticktype = "detailed"
          )

plot1 with colvar missing

Now, if you want to assign colors based on the index/number of the 8 points, you can add colvar and assign to, for example, first 4 values as 1 for black and second 4 values as 2 for red:

scatter3D(x = sep.l, y = pet.l, z = sep.w,
          pch = 19,
          bty = "b2",
          colkey = FALSE,
          phi = 15,
          theta = 30,
          col=c(rep("black", 4), rep("red", 4)),
          ticktype = "detailed",
          colvar = c(rep(1, 4), rep(2, 4)))

plot2 with colvar included

You can consider another vector for colvar that would make sense for coloring your points; just be sure it is the same length as your x, y, and z data.