Smooth 2D surface

ε祈祈猫儿з 提交于 2019-12-04 01:55:53
library(ggplot2)
library(reshape2)

set.seed(101)
## set dimnames so that melt() picks them up
m <- matrix(rnorm(20),5,dimnames=list(x=1:5,y=1:4))

plot2d_1 <- melt(m,value.name="z")

gg0 <- ggplot(plot2d_1, aes(x,y,z=z,fill=z))

The easiest way to smooth this plot is to use geom_raster() with interpolate=TRUE (see ?geom_tile for other advantages).

gg0 + geom_raster(interpolate=TRUE)

You can also do (bilinear) interpolation by hand, using the fields package (there are lots of options: e.g. library(sos); findFn("{bilinear interpolation}").

library(fields)
m2 <- interp.surface.grid(list(x=1:5,y=1:4,z=m),
              grid.list=list(x=seq(1,5,length=101),
                             y=seq(1,4,length=101)))
dimnames(m2$z) <- list(x=m2$x,y=m2$y)

Now melt it and replot:

plot2d_2 <- melt(m2,value.name="z")
gg0 %+% plot2d_2 + geom_tile()    

Hmm, the interpolation seems to have changed the z-scale - you should be careful with that ...

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