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()
:
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 viate()
, you can specifyk
for both dimensions of the spline. To setk = 5
in both directions usete(x, y, k = 5)
. To have different basis dimensions usete(x, y, k = c(10,5))
for example to have dimension 10 basis functions forx
and dimension 5 fory
.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 thete()
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.