2

I have a 30 x 16 x 9 matrix that I would like to visualize via a 4-D plot in R. I have tried scatter3D() in packages plot3d and scatterplot3d.

      x <- seq(10, 300, 10)
      y <- seq(5.0, 20.0, 1.0)
      z <- c(seq(0.5, 4, 0.5), 10)
      scatter3D(x, y, z, colvar = data)

It always gives error saying that y should have same length as x. How do I deal with this? Why do x, y, z have to be equal length? This is so inconvenient.

Werner Hertzog
  • 2,002
  • 3
  • 24
  • 36
harmony
  • 111
  • 1
  • 9
  • 3
    To plot a point in 3-dimensional space you need to know the three spatial coordinates of that point, for example, (x, y, z) or (latitude, longitude, altitude). If I just gave you the x coordinate of a point, it's location on the y-z plane could be anywhere. Thus, `scatter3D` requires three spatial coordinates for each point you want to plot. That's why the x, y, and z vectors must be the same length. The answers provide details on how to do this with code. – eipi10 May 17 '18 at 18:39
  • ahhhh, I see~~~ x, y, z should correspond to the x, y, z coordinate of each point I am gonna plot. Thanks! – harmony May 18 '18 at 00:06

2 Answers2

3

This happens because each point must have three values for this plot. You have 30 values for x, 16 values for y and 9 values for z. With this data, only the first 9 points will have the x-y-z value. In the comments of your question, eipi10 gives a very good explanation about this. An alternative, for example, is to interpolate the data to create the missing values. More about data interpolation.

library("plot3D")
number_of_points <- 50
xx <- seq(10, 300, 10)
yy <- seq(5.0, 20.0, 1.0)
zz <- c(seq(0.5, 4, 0.5), 10)

xx <- approx(x = xx, method="linear", n=number_of_points, ties = mean)$y
yy <- approx(x = yy, method="linear", n=number_of_points, ties = mean)$y
zz <- approx(x = zz, method="linear", n=number_of_points, ties = mean)$y

scatter3D(xx, yy, zz)

Hope it helps!

tk3
  • 990
  • 1
  • 13
  • 18
2

You say you have a matrix, but what you have is three vectors. You first need to create the "matrix" (here we will make a data.frame named df using expand.grid):

x <- seq(10, 300, 10)
y <- seq(5.0, 20.0, 1.0)
z <- c(seq(0.5, 4, 0.5), 10)

df <- expand.grid(x = x, y = y, z = z)

Then we can plot using the scatter3d function from the car package using either method:

car::scatter3d(x ~ y + z, data = df)
car::scatter3d(df$x, df$y, df$z)

3d plot

JasonAizkalns
  • 20,243
  • 8
  • 57
  • 116