问题
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