简体   繁体   English

如何在R中的同一图上绘制两个3D图

[英]How to plot two 3D graphs on the same plot in R

I'm using the plot3d function in the library rgl . 我在库rgl使用plot3d函数。 Suppose my data looks something like this. 假设我的数据看起来像这样。

    x <- c(1,2,3,4,5)
    y <- c(4,2,1,4,2)
    z <- c(2,2,4,5,1)

    x2 <- c(1,5,2,3,4)
    y2 <- c(2,3,4,1,2)
    z2 <- c(3,4,2,3,1)

    plot3d(x, y, z)
    plot3d(x2, y2, z2)

Using the commands above would give me 2 separate plots. 使用上面的命令将给我2个单独的图。 How can I plot both datasets on the same graph? 如何在同一张图上绘制两个数据集? Also I would like to use different symbols for the points in the two different data sets. 我也想对两个不同数据集中的点使用不同的符号。

I just wrote a function cube and an accompanying one that might be sufficient for your needs: 我刚刚编写了一个功能多维数据集和一个随附的功能多维数据集,可能足以满足您的需求:

require(rgl); library('magrittr')
cube <- function(x=0,y=0,z=0, bordered=TRUE, 
                 filled = TRUE, lwd=2, scale=1,
                 fillcol = gray(.95),
                 bordercol ='black', ...) {

  mytetra <- cube3d()

  # Reduce size to unit
  mytetra$vb[4,] <- mytetra$vb[4,]/scale*2

  for (i in 1:length(x)) {
    # Add cube border
    if (bordered) {
      btetra <- mytetra
      btetra$material$lwd <- lwd
      btetra$material$front <- 'line'
      btetra$material$back <- 'line'
      btetra %>% translate3d(x[i], y[i], z[i]) %>% shade3d
    }
    # Add cube fill
    if (filled) {
      ftetra <- mytetra
      ftetra$vb[4,] <- ftetra$vb[4,]*1.01
      ftetra$material$col <- fillcol
      ftetra %>% translate3d(x[i], y[i], z[i]) %>% shade3d
    }
  }
}

tetra <- function(x=0,y=0,z=0, bordered=TRUE, 
                             filled = TRUE, lwd=2, scale=1,
                             fillcol = gray(.95),
                             bordercol ='black', ...) {

  mytetra <- tetrahedron3d()

  # Reduce size to unit
  mytetra$vb[4,] <- mytetra$vb[4,]/scale*2

  for (i in 1:length(x)) {
    # Add cube border
    if (bordered) {
      btetra <- mytetra
      btetra$material$lwd <- lwd
      btetra$material$front <- 'line'
      btetra$material$back <- 'line'
      btetra %>% translate3d(x[i], y[i], z[i]) %>% shade3d
    }
    # Add cube fill
    if (filled) {
      ftetra <- mytetra
      ftetra$vb[4,] <- ftetra$vb[4,]*1.01
      ftetra$material$col <- fillcol
      ftetra %>% translate3d(x[i], y[i], z[i]) %>% shade3d
    }
  }
}

plot3d(x,y,z)
tetra(x,y,z, scale=1/2)
cube(x2,y2,z2, scale=1/2)

两个重叠的绘制形状集。

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

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