Mapping a variable over a spatial grid with R

Recently, I have found myself wanting to visualize the spatial distribution of some variable(s) over a map quite often. One approach that I have found particularly useful involves mapping the variable over a grid.

After a bit of trial and error, I think I have developed a fairly efficient way of doing so. In R, I’d run:

library(dplyr, sf, mapview)

sf_object <- dataframe |> st_as_sf(
  coords = c("longitude", "latitude"), 
  crs = 2154 # pick the relevant CRS
  ) 

grid <- sf_object |> 
  st_make_grid(cellsize = c(100, 100), square = TRUE) |> # this will create 100m by 100m cells
  st_as_sf() |> 
  mutate(grid_id = row_number())

sf_object_with_grid <- sf_object |> 
  st_join(grid, join = st_within) # this is where the magic happens
  group_by(grid_id) |> 
  summarize(mean_value_of_your_variable = mean(your_variable, na.rm = TRUE), n = n(), .groups = 'drop') |> 
  # optionally, you can keep cells with more than a certain number of observations
  filter(n >= 5)

Essentially, this does three things:

  1. It converts your dataframe into a spatial object ready to be mapped.
  2. It then creates a grid over the area represented by the points contained in your sf_object.
  3. It uses st_join() to assign points from your sf_object to cells in the grid you just created, and computes the mean of your variable of interest for each cell.

Then, you can use the mapview package to display the results!

map <- sf_object_with_grid |> mapview(
  zcol = "mean_value_of_your_variable",
  at = seq(lower_bound, upper_bound, by = step_size), # modify to your taste
  col.regions = viridis::viridis(number_of_colors_you_want),
  ...
)

map