2016-11-15 98 views
7

我有一個列表a三個矩陣和一個矢量h三個高度(任何正實數)。這些矩陣形成三角形,即棱鏡的底部。我想添加矢量h的信息來構建棱鏡。使用ggplot2繪製3D棱鏡並繪圖

我創建了一個函數來繪製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) 

圖形所需

An example desired

當座標a = db = fc = e是頂點,所有的信息都在a

觀察1:數據必須列表。

觀察2:我用葡萄牙語創建了一個帖子,但沒有人回答。我可以做這個還是作弊? (我是新來的) https://pt.stackoverflow.com/questions/165538/plotar-figuras-3d-para-dados-em-lista

+0

我想ggplot沒有做3D。你能否指出我們這個假設被證明是不正確的例子? –

+0

可以看到一個例子:https://www.r-bloggers.com/3d-plots-with-ggplot2-and-plotly/ –

+0

當我閱讀那個博客時,那是在做3D razzmatazz。 –

回答

4

我不是100%確定我正確理解了任務。不過,這裏有一個rgl包的解決方案草案。在我看來,它仍然是R最好的三維繪圖框架,因爲它比JavaScript API(劇情,rthreejs等)快得多,尺度也更好。

#### 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) 

結果: enter image description here

+0

非常感謝! –