Plotting lines between two points in 3D - r

I am writing an regression algorithm which tries to "capture" points inside boxes. The algorithm tries to keep the boxes as small as possible, so usually the edges/corners of the boxes go through points, which determines the size of the box.
Problem: I need graphical output of the boxes in R. In 2D it is easy to draw boxes with segments(), which draws a line between two points. So, with 4 segments I can draw a box:
plot(x,y,type="p")
segments(x1,y1,x2,y2)
I then tried both the scatterplot3d and plot3d package for 3D plotting. In 3D the segments() command is not working, as there is no additional z-component. I was surprised that apparently (to me) there is no adequate replacement in 3D for segments()
Is there an easy way to draw boxes / lines between two points when plotting in three dimensions ?

The scatterplot3d function returns information that will allow you to project (x,y,z) points into the relevant plane, as follows:
library(scatterplot3d)
x <- c(1,4,3,6,2,5)
y <- c(2,2,4,3,5,9)
z <- c(1,3,5,9,2,2)
s <- scatterplot3d(x,y,z)
## now draw a line between points 2 and 3
p2 <- s$xyz.convert(x[2],y[2],z[2])
p3 <- s$xyz.convert(x[3],y[3],z[3])
segments(p2$x,p2$y,p3$x,p3$y,lwd=2,col=2)
The rgl package is another way to go, and perhaps even easier (note that segments3d takes points in pairs from a vector)
plot3d(x,y,z)
segments3d(x[2:3],y[2:3],z[2:3],col=2,lwd=2)

Related

R generate points with condition using runifpoint function

I am trying to generate randomly distributed points in a rectangle.
To create 50 random points in a rectangle, I used
i=50
pp<-runifpoint(i, win=owin(c(0,19.5),c(0,3.12))
If I were to add conditions on the coordinates before randomly generating points,
e.g. 0.24 <x<19.26 ,0.24<y<2.64 ,
then generate random points, what code can I imply?
The ultimate goal is to generate points in the rectangle except for the grey shaded area, in the below image
This is a question about the R package spatstat.
The argument win specifies the spatial region in which the points will be generated. In your example you have specified this region to be a rectangle. You just need to replace this rectangle by the region in which you want the points to be generated.
You can construct spatial regions (objects of class owin) in many ways. See help(owin), or help(spatstat) for an overview.
In your example, you could build up the shape by forming the union of several rectangles. For example to make a simple cross shape, I could just write
require(spatstat)
A <- owin(c(-1,1), c(-4, 4))
B <- owin(c(-4,4), c(-1,1))
U <- union.owin(A, B)
plot(U)
Another way would be to specify the corners of the polygon shape and use W <- owin(poly=p) where p = list(x, y) contains the coordinates of the corners, listed in anticlockwise order without repetition. See help(owin).
This is also covered in Section 3.5 of the spatstat book. You can download Chapter 3 for free.

Plotting ellipsoids / oblate spheroids in rgl

I have been using rgl to plot spheres, but now I need to plot ellipsoids.
The package includes ellipse3d; however, this seems to be for fitting ellipsoids to data, using matrices and stuff I'm not very good at.
What I want is a simple way to plot ellipsoids, in a similar way to spheres, using the centre coordinates and the scales in each direction. Can anyone help me out?
If you don't need the ellipse rotated around the axes, then you can just use a diagonal matrix for x (this plots a sphere, and defines the virtual "axes" along the x, y, z axes) and use the centre and scale parameters to shift the location and change the proportions.
plot3d(ellipse3d(diag(3),centre=c(1,2,4),scale=c(1,2,5)))
There's one in my cda package,
library(cda)
library(rgl)
## single ellipsoid
plot3d(rgl.ellipsoid(a=2,b=1,c=5))
## multiple ellipsoids, translated and rotated
cl <- helix(0.5, 1, 36, delta=pi/6, n.smooth=1e3)
sizes <- equal_sizes(0.04,0.02,0.02,NROW(cl$positions))
rgl.ellipsoids(cl$positions, sizes, cl$angles, col="gold")

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)

Why is my plot3d white in SciLab?

t = 0:%pi/50:10*%pi;
plot3d(sin(t),cos(t),t)
When I execute this code the plot is done but the line is not visible, only the box. Any ideas which property I have to change?
Thanks
The third argument should, in this case, be a matrix of the size (length arg1) x (length arg2).
You'd expect plot3d to behave like an extension of plot and plot2d but it isn't quite the case.
The 2d plot takes a vector of x and a vector of y and plots points at (x1,y1), (x2,y2) etc., joined with lines or not as per style settings. That fits the conceptual model we usually use for 2d plots - charting the relationship of one thing as a function of another, in most cases (y = f(x)). THere are other ways to use a 2d plot: scatter graphs are common but it's easy enough to produce one using the two-rows-of-data concept.
This doesn't extend smoothly to 3d though as there are many other ways you could use a 3d plot to represent data. If you gave it three vectors of coordinates and asked it to draw a line between them all what might we want to use that for? Is that the most useful way of using a 3d plot?
Most packages give you different visualisation types for the different kinds of data. Mathematica has a lot of 3d visualisation types and Python/Scipy/Mayavi2 has even more. Matlab has a number too but Scilab, while normally mirroring Matlab, in this case prefers to handle it all with the plot3d function.
I think of it like a contour plot: you give it a vector of x and a vector of y and it uses those to create a grid of (x,y) points. The third argument is then a matrix whose dimensions match those of the (x,y) grid holding the z-coordinates of each point. The first example in the docs does what I think you're after:
t=[0:0.3:2*%pi]';
z=sin(t)*cos(t');
plot3d(t,t,z);
The first line creates a column vector of length 21
-->size(t)
ans =
21. 1.
The second line computes a 21 x 21 matrix of products of the permutations of sin(t) with cos(t) - note the transpose in the cos(t') element.
-->size(z)
ans =
21. 21.
Then when it plots them it draws (x1,y1,z11), (x1,y2,x12), (x2,y2,z22) and so on. It draws lines between adjacent points in a mesh, or no lines, or just the surface.

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