简体   繁体   English

将R中的二维plot推广到3D

[英]Generalizing a 2D plot to 3D in R

I have a problem where I have data with (x,y) coordinates that I want to plot in the xy plane.我有一个问题,我想要在 xy 平面中使用 (x,y) 坐标的数据 plot。 Furthermore, I have some box constraints such that -7 < x < 7 and -5 < y < 5 need to be drawn and checked.此外,我有一些框约束,因此需要绘制和检查 -7 < x < 7 和 -5 < y < 5。 All points that fall outside of this box constraint I would like to color red.所有落在这个盒子约束之外的点我想涂成红色。 To do this I have the following code in R:为此,我在 R 中有以下代码:

library(rgl)

x <- 7
y <- 5

data.x <- rnorm(10,0,5)
data.y <- rnorm(10,0,5)


plot(data.x, data.y, xlim = c(min(-x,data.x),max(x,data.x)), 
     ylim = c(min(-y,data.y),max(y,data.y)), pch = 19)
rect(-x, -y, x, y, col = "lightgrey")

idx <- abs(data.x) > x | abs(data.y) > y
points(data.x[idx], data.y[idx], col = "red", pch = 19)
points(data.x[!idx], data.y[!idx], col = "deepskyblue", pch = 19)

Now, where I am stuck, is on how to plot this type of data picture when I have a third group of data and a third constraint.现在,我遇到的问题是,当我有第三组数据和第三个约束时,如何 plot 这种类型的数据图片。 Ie, IE,

### How to generalize when I have a third axis and constraint, i.e., a 3D cube
z <- 4
data.z <- rnorm(10, 0, 5)

So essentially I want to plot a box constraint as a cube in the xyz plane, and to color the points that fall outside the box constraint red again.所以基本上我想要 plot 一个框约束作为 xyz 平面中的立方体,并再次将落在框约束之外的点着色为红色。

Also, I should say I understand there are functions for plottig 3d scatter plots in R, however, what I am struggling with is how to draw the 3D cube that defines the constraints.另外,我应该说我知道 R 中有 plottig 3d 散点图的函数,但是,我正在努力的是如何绘制定义约束的 3D 立方体。

The difficulty with a 3D plot such as this is being able to interpret the "depth" of the points in the image.像这样的 3D plot 的困难在于能够解释图像中点的“深度”。 An animated 3D image might be helpful here:动画 3D 图像在这里可能会有帮助:

library(plot3D)

x <- 7
y <- 5
z <- 6

set.seed(123)

data.x <- rnorm(10, 0, 5)
data.y <- rnorm(10, 0, 5)
data.z <- rnorm(10, 0, 5)

in_out <- abs(data.x) > x | abs(data.y) > y | abs(data.z) > z

for(i in seq(0, 358, 2)) {

  png(paste0("box", sprintf("%03d", i), ".png"))
  box3D(-x, -y, -z, x, y, z, col = NA, border = "gray50", theta = i, phi = 15,
        xlim = c(-10, 10), ylim = c(-10, 10), zlim = c(-10, 10),
        axes = TRUE, ticktype = "detailed")

  points3D(data.x, data.y, data.z, colvar = in_out, pch = 16, cex = 3, 
           add = TRUE, colkey = FALSE, col = c("lightblue", "red"))
  dev.off()
}

library(magick)

list.files(pattern = 'box\\d+\\.png', full.names = TRUE) %>% 
  image_read() %>% 
  image_join() %>% 
  image_animate(fps=50) %>% 
  image_write("box.gif") 

box.gif盒子.gif 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM