How can I create a surface plot with missing values in R?

自闭症网瘾萝莉.ら 提交于 2019-12-31 01:58:06

问题


I have an example 5x5 matrix with the following values:

dat <- matrix(seq(1,13,0.5), nrow=5, byrow=TRUE)
dat[seq(2,25,2)] <- NA

 1 | NA |  2 | NA |  3
NA |  4 | NA |  5 | NA
 6 | NA |  7 | NA |  8
NA |  9 | NA | 10 | NA
11 | NA | 12 | NA | 13

I cannot for the life of me get a 3D surface plot using for example persp3d() because of the missing values. Isn't there a way that R can just interpolate the values and still plot them?


回答1:


While this might have been asked before, I couldn't find a neat worked example of this circumstance. Try this, which will give a result you can then pass to persp, image etc...

#install.packages("akima")
library(akima)

nas <- !is.na(dat)
interp(
  row(dat)[nas],       #row index   - 'x' values
  col(dat)[nas],       #col index   - 'y' values
  dat[nas],            #height data - 'z' values
  xo=seq(1,nrow(dat)), #'x' values for output
  yo=seq(1,ncol(dat))  #'y' values for output
)

#$x
#[1] 1 2 3 4 5
# 
#$y
#[1] 1 2 3 4 5
#
#$z
#     [,1] [,2] [,3] [,4] [,5]
#[1,]  1.0  1.5  2.0  2.5  3.0
#[2,]  3.5  4.0  4.5  5.0  5.5
#[3,]  6.0  6.5  7.0  7.5  8.0
#[4,]  8.5  9.0  9.5 10.0 10.5
#[5,] 11.0 11.5 12.0 12.5 13.0


来源:https://stackoverflow.com/questions/30113019/how-can-i-create-a-surface-plot-with-missing-values-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!