【问题标题】:How to Draw a three-dimensional graph in R如何在 R 中绘制三维图
【发布时间】:2018-10-21 17:14:34
【问题描述】:
f(x,y)= (1/25)*(20-x)/x   10<x<20, x/2 <y <x
        0                   o.t

我必须通过这个表达式来创建这个图像。

但是

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)

怎么了?

【问题讨论】:

  • 欢迎来到 Stack Overflow!
  • 欢迎。请查看stackoverflow.com/questions/5963269/…,了解发布问题时的最佳做法。
  • 如果下面的答案令人满意,你应该“接受”它。如果没有,你应该解释你还想要什么,它的作者可能会尝试改进它。

标签: r plot rgl


【解决方案1】:

您应该根据约束屏蔽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)

【讨论】:

    【解决方案2】:

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

    可能会更好的填充一些左右边缘,用更多的点来避开那些大三角形, 但暂时跳过。

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

    旋转后,你会得到这个视图:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-05
      • 2016-02-14
      相关资源
      最近更新 更多