Location heatmaps in R

Location heatmaps in R

Let’s use a built-in example within R: location of earthquakes off the island of Fiji.

#>      lat   long depth mag stations
#> 1 -20.42 181.62   562 4.8       41
#> 2 -20.62 181.03   650 4.2       15
#> 3 -26.00 184.10    42 5.4       43
#> 4 -17.97 181.66   626 4.1       19
#> 5 -20.42 181.96   649 4.0       11
#> 6 -19.68 184.31   195 4.0       12

This data set contains spatial point data of earthquakes modelled with a certain magnitude and focal depth using observations from a certain number of observatories (stations).

Take a shape and setup the base map

#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1
#> Loading required package: htmlwidgets
#> tmap mode set to interactive viewing

Create a grid

This makes an outline and is a good check to see if the bounding box is correct

#> although coordinates are longitude/latitude, st_intersects assumes that they are planar

Now divide into a grid with cells. In the case below we divide the bounding box region into 20 cells of equal size and equal length in both dimensions.

#> although coordinates are longitude/latitude, st_intersects assumes that they are planar

Join and aggregate

Form a spatial join with the point observations. Group by id of the cell and any group variables in the point observations (such as measurement type, date, object, etc.). Then aggregate, e.g., by summing or calculating the mean of all observations associated with that cell.

#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
#> although coordinates are longitude/latitude, st_intersects assumes that they are planar
#> `summarise()` ungrouping output (override with `.groups` argument)

A true heatmap

The above wasn’t really a heatmap so much as a grid. Fortunately the leaflet package has a built in function that is able to render heatmaps properly. Or rather it is contained in the leaflet.extras package.

Richard Davey
Richard Davey
Analytical Consultant

My interests include earth science, numerical modelling and problem solving through optimisation.

Related