使用ggplot2和plotly绘制3D棱镜

Wag*_*rge 7 3d graphics r ggplot2

我有一个a包含三个矩阵的列表和一个h有三个高度的矢量(任何正实数).这些矩阵形成三角形,即棱镜的基底.我想添加矢量信息h来构建棱镜.

我创建了一个在2D(pplot)中绘制图形的函数.如何绘制棱镜,如下图所示?

让我们pplot玩具的问题是一个例子:

library(ggplot2)
pplot <- function(polygon){
  polygon <- lapply(polygon, function(x) {colnames(x) <- NULL; x})
  vertex_number = nrow(polygon[[1]])
  g = ggplot2::ggplot()
  names(polygon) = 1:length(polygon)
  k <- plyr::ldply(polygon, function(x) data.frame(x))
  g <- ggplot2::ggplot(k, ggplot2::aes(x = X1, y = X2, group = .id)) + ggplot2::geom_polygon(colour = "black", fill = NA)
  return(g)
}

a <- list()
b1 <- matrix(rnorm(6), ncol = 2)
b2 <- matrix(rnorm(6), ncol = 2)
b3 <- matrix(rnorm(6), ncol = 2)

a[[1]] <- b1
a[[2]] <- b2
a[[3]] <- b3

h <- c(.3, .5, .1)
#pplot function example
pplot(a) 
Run Code Online (Sandbox Code Playgroud)

图形需要

一个期望的例子

当坐标a = d,b = f,c = e是顶点,所有的信息在a.

观察1:数据必须列表.

观察2:我用葡萄牙语创建了一个帖子,但没有人回答.我可以这样做还是作弊?(我是新来的) https://pt.stackoverflow.com/questions/165538/plotar-figuras-3d-para-dados-em-lista

nev*_*ome 4

我不能 100% 确定我正确理解了该任务。不过,这里有一个包解决方案的草案rgl。在我看来,它仍然是最好的 R 3D 绘图框架,因为它比 javascript API(plotly、r Threejs 等)更快且可扩展性更好。

#### load package rgl ####
library(rgl)

set.seed(1232)

#### construct test list with coordinate matrices ####
a <- list()
b1 <- matrix(rnorm(6), ncol = 2)
b2 <- matrix(rnorm(6), ncol = 2)
b3 <- matrix(rnorm(6), ncol = 2)

a[[1]] <- b1
a[[2]] <- b2
a[[3]] <- b3

#### define test height vector ####
h <- c(.3, .5, .1)

#### simple plot prism function ####
# a: list with coordinate matrices
# h: height vector
plotprism <- function(a, h){
  # general loop to plot every prism
  for(i in 1:length(h)){
    # transform matrizes to data.frames and add height column 
    # -> separation of top and bottom triangle
    top <- data.frame(a[[i]], h[i]) 
    bottom <- data.frame(a[[i]], 0) 
    # adjust colnames to axis names
    colnames(top) <- c("x", "y", "z") 
    colnames(bottom) <- c("x", "y", "z") 
    # plot triangles (as wireframes)
    triangles3d(bottom, front = "line", back = "line")
    triangles3d(top, front = "line", back = "line")
    # plot vertical lines to connect the triangles
    for(i in 0:2){
      segments3d(
        x = c(bottom$x[1+i], top$x[1+i]),
        y = c(bottom$y[1+i], top$y[1+i]),
        z = c(bottom$z[1+i], top$z[1+i])
      )
    }
  }
  #### add coordinate system ####
  axes3d()
}

#### call plot function for test data ####
plotprism(a, h)
Run Code Online (Sandbox Code Playgroud)

结果: 在此输入图像描述