GeoPandas Heatmaps

Simple demonstration of generating heatmap plots from geopandas point geodataframes

In [1]:
%matplotlib inline
import geopandas as gpd
import numpy as np
from scipy import ndimage

import matplotlib.pylab as pylab
import matplotlib.pyplot as plt
pylab.rcParams['figure.figsize'] = 8, 6

Load the point data and plot it to see the pattern...

In [6]:
pts = gpd.GeoDataFrame.from_file('points_demo.shp')
In [3]:
<matplotlib.axes.AxesSubplot at 0x7f61dc5ddc90>

Now we define the heatmap function which takes a GeoDataFrame with point geometries and shows a matplotlib plot of heatmap density. This is done using numpy's 2D histogram binning with smoothing from scipy.

In [7]:
def heatmap(d, bins=(100,100), smoothing=1.3, cmap='jet'):
    def getx(pt):
        return pt.coords[0][0]

    def gety(pt):
        return pt.coords[0][1]

    x = list(d.geometry.apply(getx))
    y = list(d.geometry.apply(gety))
    heatmap, xedges, yedges = np.histogram2d(y, x, bins=bins)
    extent = [yedges[0], yedges[-1], xedges[-1], xedges[0]]

    logheatmap = np.log(heatmap)
    logheatmap[np.isneginf(logheatmap)] = 0
    logheatmap = ndimage.filters.gaussian_filter(logheatmap, smoothing, mode='nearest')
    plt.imshow(logheatmap, cmap=cmap, extent=extent)
In [8]:
heatmap(pts, bins=50, smoothing=1.5)