Strange object in vector3d() graphic when using matlib + rgl - r

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!

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).

Related

Plotting 3D GIF in R

I was working with 3 vectors x , y , z , each of length N (Assume N to be some large natural number, say 20000). In order to visualize this, I was able to plot this easily using the following R code :
library("plot3D")
lines3D(x, y, z, type = "l")
Now, I was thinking if we can make a little 3D animation (i.e. a 3D GIF) from the vectors x , y , z. Is it possible in R ?
NOTE : I've previously done 2D GIFs in R, with the help of packages like ggplot2 , gganimate , magick etc. However, I'm curious whether the same thing can be done for 3D data. Thanks in advance.
It is very simple to create .gif with the animation package (note it requires ‘ImageMagick’ or ‘GraphicsMagick’ to run). After the installation, you could do something like this (I assume that you want to display your plot with different point of view):
library(plot3D)
library(animation)
x <- runif(1000)
y <- x*2+runif(1000)
z <- sample(1:10,length(x),replace = T)*x/y
ani.options(interval=0.5,nmax=35)
saveGIF(for(t in seq(0,360,10)){
lines3D(x, y, z, type = "l",theta=t)
}, movie.name = "animation.gif")

Play3d in RGL package

I am working on a project using the RGL package in R programming. I would love if someone could help me with the play3d function of the same.
Here is what I plan to do. I have a polygon3d(x,y,z) that plots a polygon on the output window and now I would want to translate it with some value at each iteration, say by 10 units for 5 rounds.
I researched but all the available resources are about rotation of the polygon for t-duration. Example of such a case is:
M <- par3d("userMatrix")
play3d(
par3dinterp(userMatrix=list(M,rotate3d(M, angle=pi, x=1 ,y=0, z=0))),
duration=10
)
The above code rotates my polygon along x-axis for 10seconds and stops.
I want to translate my polygon for 10 seconds with some given parameters specifying how much to translate at each second.
My polygon is basically a plus sign(representing a quadcopter) and I want to show the motion as if it is elevating from the ground(x-y axis) into the air(z-axis).
Any help will be deeply appreciated.
Thanks all
You need to use the transpose of a translation matrix to do this. For example, to translate by (x, y, z), use
M <- par3d("userMatrix")
play3d(
par3dinterp(userMatrix=list(M, M %*% t(translationMatrix(x, y, z)))),
duration=10
)
This is done in the ?rgl.setMouseCallbacks example.
Edited to add x, y, z values to answer question below.

Creating a hexplot

I am trying to create a figure like the one depicted in the third column of the following image:
Link for the image in case of backup.
Basically I have x and y positions of 200 particles and I have the MSD data for these 200 positions. I'd like MSD to be the value that should determine a color map for the particles in coordinates (x,y). So MSD should be like the height, or the z position corresponding to each particle in (x,y).
I am surprised at my incompetence, because I have been trying to solve this problem for the last couple of days but none of the Google searches gave me any result. The closest thing that I have found is the concept of "self-organizing map" in Matlab and R, but I do not know how to use R and Matlab's toolbox for SOM was utterly useful for my needs.
I tried the following code in Matlab and get the attached plot as a result:
clear all; close all; clc;
x = (dlmread('xdata.dat'))'; % x is 1x200 array
y = (dlmread('ydata.dat'))'; % y is 1x200 array
msd = (dlmread('msd_field.txt'))'; % msd is 1x200 array
[X,Y] = meshgrid(x,y);
Z = meshgrid(msd);
z = [X; Y; Z];
surf(z)
But I think this plot is not useful at all. What I want is a 2D scatter plot of (x,y) depicting particle positions and on top of that color code this scatter plot with the values stored in msd like the plot I showed in the beginning. How can I create this through Matlab, or any other visualization tool? Thank you in advance.
It is not clear whay you want to have. Here a scatter plot using ggplot2.
## some reproducible data
set.seed(1)
dat <- data.frame(
x = round(runif(200,-30,30),2),
y = round(runif(200,-2,30),2),
msd = sample(c(0,2,3),200,rep=T))
## scatter plot where the size/color of points depends in msd
library(ggplot2)
ggplot(dat) +
geom_point(aes(x,y,size=msd,color=msd)) +
theme_bw()

polar image plot, how to do it with R?

I cannot find a straightforward way to make a nice image plot in R, but in polar coordinates. I'm basically attempting to find a R equivalent for the 'polarplot3d' function in MATLAB. I've been playing around with ggplot2 package but without much luck. Am I missing a package that contains functionality for what I'm attempting? thanks in advance for any pointers.
Ok, I'm trying to be more clear about what I'm trying to do. Lets say I want to define a polar coordinate grid, increments in the radial direction are 50m and 2.5 degrees in theta. This should look like a dartboard.
My data (r and angle in below code) are correspond to a radial distance measure and an angle. My desired z-value is the counts of a bivariate histogram between r and angle within the increments described above defining the grid.
My data is like the following:
# synthetic data for angle and distance #
angle <- rnorm(500,mean=90,sd=15)
r <- rnorm(500,mean=700,sd=200)
# bivariate histogram #
observations <- table(cut(angle,breaks=c(seq(0,360,by=2.5))),cut(r,breaks=c(seq(0,1400,by=50))))
# the 'z' data are in observations for each bin of bivariate histogram #
# hot to plot a polar coord image? #
It's very slow to render on my system, but
library(reshape2)
library(ggplot2)
mm <- melt(counts)
ggplot(mm,aes(Var1,Var2,fill=value))+geom_tile()+coord_polar()
ggsave("polar1.png")
appears to work.
I think the following could work. Use mapproject() from the maproj library to transform my xy coordinates acording to a polar projection (or another), Then use as.image() (from fields package) function to build a image object from my new coordiantes and my Z values. Eventually use image.plot().
library("mapproj")
xyProj <- mapproject(x, y, projection="conic", parameters=-90)
library("fields")
im <- as.image(z, x=xyProj)
image.plot(im)

Make a 3D rendered plot of time-series

I have a set of 3D coordinates (below - just for a single point, in 3D space):
x <- c(-521.531433, -521.511658, -521.515259, -521.518127, -521.563416, -521.558044, -521.571228, -521.607178, -521.631165, -521.659973)
y <- c(154.499557, 154.479568, 154.438705, 154.398682, 154.580688, 154.365189, 154.3564, 154.559189, 154.341309, 154.344223)
z <- c(864.379272, 864.354675, 864.365479, 864.363831, 864.495667, 864.35498, 864.358582, 864.50415, 864.35553, 864.359863)
xyz <- data.frame(x,y,z)
I need to make a time-series plot of this point with a 3D rendering (so I can rotate the plot, etc.). The plot will visualize a trajectory of the point above in time (for example in the form of solid line). I used 'rgl' package with plot3d method, but I can't make it to plot time-series (below, just plot a single point from first frame in time-series):
require(rgl)
plot3d(xyz[1,1],xyz[1,2],xyz[1,3],axes=F,xlab="",ylab="",zlab="")
I found this post, but it doesn't really deal with a real-time rendered 3D plots. I would appreciate any suggestions. Thank you.
If you read help(plot3d) you can see how to draw lines:
require(rgl)
plot3d(xyz$x,xyz$y,xyz$z,type="l")
Is that what you want?
How about this? It uses rgl.pop() to remove a point and a line and draw them as a trail - change the sleep argument to control the speed:
ts <- function(xyz,sleep=0.3){
plot3d(xyz,type="n")
n = nrow(xyz)
p = points3d(xyz[1,])
l = lines3d(xyz[1,])
for(i in 2:n){
Sys.sleep(sleep)
rgl.pop("shapes",p)
rgl.pop("shapes",l)
p=points3d(xyz[i,])
l=lines3d(xyz[1:i,])
}
}
The solution was simpler than I thought and the problem was that I didn't use as.matrix on my data. I was getting error (list) object cannot be coerced to type 'double' when I was simply trying to plot my entire dataset using plot3d (found a solution for this here). So, if you need to plot time-series of set of coordinates (in my case motion capture data of two actors) here is my complete solution (only works with the data set below!):
download example data set
read the above data into a table:
data <- read.table("Bob12.txt",sep="\t")
extract XYZ coordinates into a separate matrixes:
x <- as.matrix(subset(data,select=seq(1,88,3)))
y <- as.matrix(subset(data,select=seq(2,89,3)))
z <- as.matrix(subset(data,select=seq(3,90,3)))
plot the coordinates on a nice, 3D rendered plot using 'rgl' package:
require(rgl)
plot3d(x[1:nrow(x),],y[1:nrow(y),],z[1:nrow(z),],axes=F,xlab="",ylab="",zlab="")
You should get something like on the image below (but you can rotate it etc.) - hope you can recognise there are joint centers for people there. I still need to tweak it to make it visually better - to have first frame as a points (to clearly see actor's joints), then a visible break, and then the rest of frames as a lines.

Resources