0
votes

I'm trying to plot 3-dimensional vectors (x, y, z coordinates) onto a 3D coordinate system in R like in the picture below. Ideally, I would then like to construct 3d kernel density plots, also like in the image below.

Ideal result of vector plot and 3d kernel density plot

I have a matrix containing ~100 rows and one column for each coordinate (x, y , z). Initially, I tried arrow3D() from the plot3D package but I find the perspective to be sub-par, it's rather difficult to discern directions of the arrows from one perspective in the final plot. Next I tried the rgl package which gives me interactivity - great. Minimal working example:

library(rgl)
library(matlib)

data2 <- data.frame(replicate(6,rnorm(100))) #sample data set for minimum working example

colnames(data2) <- c("x_target", "y_target", "z_target", "x_start", "y_start", "z_start")

x1 <- data2$x_target - data2$x_start
y1 <- data2$y_target - data2$y_start
z1 <- data2$z_target - data2$z_start

vec <- (diag(6,3))     # coordinates for x, y and z axis
rownames(vec) <- c("X", "Y", "Z")   # labels for x, y and z axis

z <- as.matrix((data.frame(x=x1, y=y1, z=z1)))

open3d()

vectors3d(vec, color=c(rep("black",3)), lwd=2, radius=1/25)
vectors3d(X=z, headlength=1/25)

(due to the random numbers generator the strange looking rods appear at different coordinates, not exactly like in the image i link to below)

The result of the code above is a version of the image link below. One set of coordinates produces a very strange looking more like rod object which is far longer then the coordinates would produce. If I plot the vectors individually, no such object is created. Anyone have any ideas why this happens? Also, if anyone has a tool (doesn't have to be R), that can create a 3D vector plot like in the first image, I'd be grateful. I find it to be very complicated in R, but I'm definitely a beginner.

Strange object to the right (long red rod that doesn't look like an arrow at all)

Thank you!

1
Where did you find the vectors3d function? It's not in rgl. And more generally: we can't reproduce your example, because we don't have x1, y1, or z1. Please post a reproducible example.user2554330
I apologize. It's from the matlib package. I will provide x1, y1, z1 right away! The code above now works on my system.Linus Köster

1 Answers

0
votes

This is due to a bug in the matlib package, fixed in verson 0.9.2 of that package. I think you need to install it from Github instead of CRAN to get the bug fix:

devtools::install_github("friendly/matlib")

BTW, if you are using random numbers in a reproducible example, you can make it perfectly reproducible by something like

set.seed(123)

at the start (or some number other than 123). I saw reproducible problems with your example for set.seed(4).