smoothing surface plot from matrix

有些话、适合烂在心里 提交于 2019-12-06 03:06:54

Whatever you end up doing, you'll need some model to smooth the data you have. You could use a wide range of models to do the smoothing but the one I am most familiar with is the penalised regression spline approach to fitting GAMs via the mgcv package, which also happens to come with R.

Firs, some simulated data

set.seed(1)
m <- matrix(runif(11*8), ncol = 8)

To model these, you need them in the form z ~ x + y, i.e. long format where there is a row for every z (cell in your matrix). So, arrange our example data into long format

df <- data.frame(x = rep(seq_len(ncol(m)), each = nrow(m)),
                 y = rep(seq_len(nrow(m)), times = ncol(m)),
                 z = c(m))

> head(df)
  x y         z
1 1 1 0.2655087
2 1 2 0.3721239
3 1 3 0.5728534
4 1 4 0.9082078
5 1 5 0.2016819
6 1 6 0.8983897

Here x varies slowest and refers to the columns, y fastest and refers to the rows. Next load mgcv and fit the model

require("mgcv")
mod <- gam(z ~ te(x, y), data = df)

The model is a 2d tensor product spline of the x and y "locations`.

To replicate your plot, but smoother, take the fitted values of the model and arrange as a matrix again

m2 <- matrix(fitted(mod), ncol = 8)

Then plot

require("lattice")
wireframe(m2)

Depending on what you are doing, you can control the degree of smoothness via two options to te():

  1. k sets the degrees of freedom or complexity of the smooths. Here is really sets the initial dimensions of the basis functions, which are then shrunk to some "optimal dimensionality via the penalised regression. For the tensor product spline fitted via te(), you can specify k for both dimensions of the spline. To set k = 5 in both directions use te(x, y, k = 5). To have different basis dimensions use te(x, y, k = c(10,5)) for example to have dimension 10 basis functions for x and dimension 5 for y.

  2. Fix the degrees of freedom, i.e. don't do any of the penalisation I mentioned above. You do this by adding fx = TRUE to the te() call. To continue the last example, te(x, y, k = c(10,5), fx = TRUE) will use the basis functions as above but won't shrink down from this to some smaller number of degrees of freedom.

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