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!
The reason you see 6 black and 2 red, is that
colvar
is missing from yourscatter3D
call to be used withcol
in coloring.In your example, the color is based on your z-axis. To demonstrate, we can add back the
colkey
, addticktype
to see axis information, and rotate a bit to show the red color is applied for values over 3.45 insep.w
(z-axis), which only includes 2 values from your data (3.6 and 3.9).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: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.