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

时间:2014-09-10 19:50:52

标签: r visualization rgl

我正在使用库plot3d中的rgl函数。假设我的数据看起来像这样。

    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)

使用上面的命令会给我2个单独的图。如何在同一图表上绘制两个数据集?另外,我想对两个不同数据集中的点使用不同的符号。

1 个答案:

答案 0 :(得分:0)

我刚刚编写了一个函数多维数据集和一个可能足以满足您需求的函数:

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)

Two overlapping plotted shape sets.