Plotting lines between two points in 3D

2020-07-05 05:32发布

问题:

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 ?

回答1:

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)


标签: r 3d plot line