Average values of a point dataset to a grid dataset

后端 未结 2 1834
我寻月下人不归
我寻月下人不归 2020-12-08 05:52

I am relatively new to ggplot, so please forgive me if some of my problems are really simple or not solvable at all.

What I am trying to do is generate a \"Heat Map\

2条回答
  •  死守一世寂寞
    2020-12-08 06:25

    I think what you want is something along these lines. I predict that this homebrew is going to be terribly inefficient for large datasets, but it works on a small example dataset. I would look into kernel densities and maybe the raster package. But maybe this suits you well...

    The following snippet of code calculates the mean value of cadmium concentration of a grid of points overlaying the original point dataset. Only points closer than 1000 m are considered.

    library(sp)
    library(ggplot2)
    loadMeuse()
    
    # Generate a grid to sample on
    bb = bbox(meuse)
    grd = spsample(meuse, type = "regular", n = 4000)
    # Come up with mean cadmium value
    # of all points < 1000m.
    mn_value = sapply(1:length(grd), function(pt) {
      d = spDistsN1(meuse, grd[pt,])
      return(mean(meuse[d < 1000,]$cadmium))
    })
    
    # Make a new object
    dat = data.frame(coordinates(grd), mn_value)
    ggplot(aes(x = x1, y = x2, fill = mn_value), data = dat) + 
       geom_tile() + 
       scale_fill_continuous(low = "white", high = muted("blue")) + 
       coord_equal()
    

    which leads to the following image:

    enter image description here

    An alternative approach is to use an interpolation algorithm. One example is kriging. This is quite easy using the automap package (spot the self promotion :), I wrote the package):

    library(automap)
    kr = autoKrige(cadmium~1, meuse, meuse.grid)
    dat = as.data.frame(kr$krige_output)
    
    ggplot(aes(x = x, y = y, fill = var1.pred), data = dat) + 
       geom_tile() + 
       scale_fill_continuous(low = "white", high = muted("blue")) + 
       coord_equal()
    

    which leads to the following image:

    enter image description here

    However, without knowledge as to what your goal is with this map, it is hard for me to see what you want exactly.

提交回复
热议问题