# Spatial kernel density in Python

I have the data of the volume per area for Madrid.

``````from mpl_toolkits.axes_grid1 import make_axes_locatable
def setColorbar(ax, colormap, vmin, vmax):
divider = make_axes_locatable(ax)
sm = plt.cm.ScalarMappable(cmap=colormap, norm=plt.Normalize(vmin=vmin, vmax=vmax))
# fake up the array of the scalar mappable. Urgh...
sm._A = []
return plt.colorbar(sm, cax=cax)

vmin=0
vmax=70
cmap='jet'
f,ax=plt.subplots(figsize=(10,10))
dfMd.plot(column='volume', alpha=0.5,ax=ax, cmap=cmap, vmin=vmin, vmax=vmax)
setColorbar(ax, cmap, vmin=vmin, vmax=vmax)
``````

I would like to find hotspot of the building density and assign to each polygon a sort of kernel density class associated to the hotspot like this example

What I have done is to define points of interest based on percentiles in this way.

``````pcts95 = np.percentile(dfMd['volume'], 95)
dfMd95 = dfMd[dfMd['volume'] >= pcts95]
dfMd95 = dfMd95.drop_duplicates(["geometry"]).reset_index(drop=True)
dfMd95 = gpd.geoseries.GeoSeries([geom for geom in dfMd95.unary_union.geoms])
dfMd95=gpd.GeoDataFrame(dfMd95)
dfMd95.columns = ['geometry']
X=[]
Y=[]
for i in dfMd95.index:
X.append(dfMd95['geometry'].centroid.x)
Y.append(dfMd95['geometry'].centroid.y)

vmin=0
vmax=70
cmap='jet'
f,ax=plt.subplots(figsize=(10,10))
dfMd.plot(column='volume', alpha=0.1,ax=ax, cmap=cmap, vmin=vmin, vmax=vmax)
setColorbar(ax, cmap, vmin=vmin, vmax=vmax)
ax.scatter(X,Y, color='black', s=75)
``````

However I would like to know if there is a way to estimate kernel density based polygons value as this example

• What about using a heatmap ? Commented Apr 12, 2021 at 8:08
• @KadirŞahbaz `dfMd` is a geopandas dataframe. However the data comes from a raster data. I just converted a geotiff image in a geopandas dataframe to make some correlations.
– emax
Commented Apr 19, 2021 at 9:22
• @emax are you trying to plot something like this (scroll to bottom)? seaborn.pydata.org/generated/seaborn.kdeplot.html If you have one point per raster cell, the `weights` parameter might be of interest to you. Your `volume` would be the weight. Commented Apr 20, 2021 at 7:19
• I'm also struggling a bit to understand the question - do you want the density as data or plotted? Assuming data, is this approach of any use? gis.stackexchange.com/questions/368894/density-per-grid-cell Commented Apr 21, 2021 at 10:26
• I would like to assign to each pixel the respective center they belong to based on the distance to the center and the "intensity" of the value. I would like to find a sort of urban polycentricity
– emax
Commented Apr 22, 2021 at 13:21