如何在R中绘制三维图形

时间:2018-10-21 17:14:35

标签: r plot rgl

f(x,y)= (1/25)*(20-x)/x   10<x<20, x/2 <y <x
        0                   o.t

我必须通过此表达式创建此图像。 enter image description here

但是 enter image description here

x <- seq(10, 20, length=20)
y <- seq(10, 20, length=20)
f <- function(x,y){(1/25)*(20-x)/5}
z <- outer(x,y,f)
persp(x,y,z,theta=30,phi=30, expand=0.5,col=rainbow(19), border=NA)

怎么了?

2 个答案:

答案 0 :(得分:0)

您应根据约束条件屏蔽z。作为建议,您可以在R中使用出色的交互式rgl包。

#source: https://stackoverflow.com/questions/50079316/plot3d-how-to-change-z-axis-surface-color-to-heat-map-color
map2color <- function(x, pal, limits = range(x,na.rm=T)){
  pal[findInterval(x, seq(limits[1], limits[2], length.out = length(pal) + 1), 
               all.inside=TRUE)]
}

x <- seq(10, 20, length=20)
y <- seq(10, 20, length=20)
mask <- sapply(x,function(m) sapply(y,function(n) if((n>m/2)&(n<m)){(1/25)*(20-m)/5}else{ NA }))
z <- outer(x,y,f)
z <- z * mask
#persp(x,y,z, col= map2color(z, rainbow(100)),border = NA)
library(rgl)
persp3d(x,y,z,col = map2color(z, rainbow(100)),theta=30,phi=30)

enter image description here enter image description here

答案 1 :(得分:0)

@SRhm的答案可能是最好的选择,但是如果您想住在最前沿,可以使用rgl(来自R-forge)的开发版本摆脱锯齿状的对角线边缘最低版本为0.100.8。

此版本使用tripack包支持带边界的三角剖分。因此,您可以在x-y范围内建立值网格,然后使用方程式定义区域的边界,然后获得平滑的边缘。例如:

library(tripack)
library(rgl)
g <- expand.grid(x=10:20, y=5:20)
keep <- with(g, 10 < x & x < 20 & x/2 < y & y < x)
g2 <- g[keep,]
tri <- tri.mesh(g2)

# Set up boundary constraints
cx <- c(10:20, 20: 10)
cy <- c(seq(5, 10, len=11), 20:10)
tri2 <- add.constraint(tri, cx, cy, reverse = TRUE)

# This isn't necessary, but shows where the formula will be evaluated
plot(tri2)

triangulation

最好用更多的点填充一些左右边缘,以避免那些大三角形, 但请暂时跳过。

z <- with(tri2, (1/25)*(20-x)/x)
# Now plot it, using the map2color function @SRhm found:
#source: https://stackoverflow.com/questions/50079316/plot3d-how-to-change-z-axis-surface-color-to-heat-map-color
map2color <- function(x, pal, limits = range(x,na.rm=T)){
  pal[findInterval(x, seq(limits[1], limits[2], length.out = length(pal) + 1), 
               all.inside=TRUE)]
}
persp3d(tri2, z, col = map2color(z, rainbow(100)))

旋转后,您将获得以下视图:

persp3d view