ggplot – How to Create a Heatmap in ggplot

ggplot2heat mapr

I'm using R with ggplot2 to generate maps from shapefiles and from data in SQL Server. I'm trying to get to a stage where I can automate a large chunk of the mapping I do. So far this is working well and I'm able to generate some fairly nice looking maps (just need to work on labelling).

I'm wondering if it's possible to create a geographical heatmap from a list of point co-ordinates (which are irregularly spaced)? Similar to using geom_density2d, but raster.

Best Answer

RTFM. Turns out that stat_density2d can do all I was asking and more.

Edit:

Still one outstanding issue with this which is that using stat_density2d with geom=tile can display some odd behaviour when trying to set the scale of the map.

In my example I am plotting a shapefile of all England & Wales, however I'm interested in the greater London area. If I allow ggplot to simply default and display the entire shapefile then the heatmapping generated by stat_density2d isn't very useful for me.

To address this I need to set the xlim and ylim to effectively zoom in. I can do this in one of two ways:

  1. Use the xlim & ylim functions in ggplot
  2. Use xlim & ylim within coord_map

The former causes the heatmapping to scale correctly (ie size of the tiles reduce to give a meaningful indication of density in a smaller area) but the shapefile data gets truncated to the plot leading to some very odd looking polygons.

The latter causes the heatmapping to remain at the scale of the whole country (ie the tiles are massive and so not useful for showing activity density) but the polygons display correctly.

I've set this as a separate question: Using stat_density2d with coord_map in ggplot2