### My question

Plotting heatmap with shapefile

### 1.intro

• a bunch of shapefile represent the administration boundaries
• a pandas.Dataframe containing some point with (longitude,latitude,value)

Code here:

`` map = Basemap(llcrnrlon=xc1,llcrnrlat=yc1,urcrnrlon=xc2,urcrnrlat=yc2)##Assuming "shape.shp" is my shapefilemap.readshapefile('./shape','shape',zorder =1,)patches=[]cs=plt.cm.Greens(np.arange(18)/18.)for info, shape in zip(map.shape_info, map.shape):x,y=zip(*shape)patches.append( Polygon(np.array(shape), True) ) # facecolor= '#6582B3'ax.add_collection(PatchCollection(patches, facecolor= cs,edgecolor='none',linewidths=1.5, zorder=2))## scatter the point, assuming "pt" is the Dataframept_lat = pt.lat.as_matrix()pt_lon = power.lon.as_matrix()plt.scatter(pt_lon,pt_lat,marker='o',s=50,lw= 0,zorder = 3, alpha = 0.75)``

Picture here:

http://i11.tietuku.com/9785abb6097b7c0e.png

### 2. My target

In the picture upward, the color of each shapefile is based on the colormap predefined.

• Plotting Each area (In my case, 18 shapefile) with the color corresponding to the sum of pt.values within.
• In other words, the inner point data decide the shapefile's color

I have learned from your code, but still has some problem.

Here is my code & picture:

`` fig = plt.figure(figsize =(8,6))ax = plt.subplot()map = Basemap(llcrnrlon=xc1,llcrnrlat=yc1,urcrnrlon=xc2,urcrnrlat=yc2)map.readshapefile('./shape','shape')patches=[]for info, shape in zip(map.shape_info, map.shape):x,y=zip(*shape)patches.append(Polygon(np.array(shape), True) )xx = pt.lon.iloc[:].as_matrix()yy = pt.lat.iloc[:].as_matrix()value = pt.value.iloc[:].as_matrix()sh = (len(xx),2)position = np.zeros(len(xx)*2).reshape(*sh)for i in range(0,len(xx),1):position[i] = np.array([xx[i],yy[i]])poly_values = []for patch in patches:mask = np.array([patch.contains_point(xy) for xy in position])poly_values.append(value[mask].sum())coll = PatchCollection(patches, cmap = 'Greens')coll.set_array(np.array(poly_values))ax.add_collection(coll)plt.colorbar(coll,label = "polygon")point_plot = plt.scatter(xx,yy,marker='o',s=80,lw= 0,zorder = 3, c = "r",alpha = 0.75)ax.set_frame_on(False)divider = make_axes_locatable(ax)cax = divider.append_axes("right", size="4%", pad=0.1)cbar = plt.colorbar(coll,label = "polygon",cax= cax)``

http://i4.tietuku.com/9a7b0cbc16f2e0b0.png

• It seems like the color for polygon[i] isn't according to the poly_value[i]
• I think the problem is `coll.set_array` doesn't work.
• Otherwise, I have checked each polygon and the scatter point value within, the poly_value[i] and the actual condition is not match(bigger than reality). I think the I may use value.mask wrong.

• You can use `Polygon.contains_point` to check if a point is inside it.

• I use this function to create a boolean mask to address the points which are inside that poly and use `.sum()` to get the value for this polygon.

• Then I use `PatchCollection.set_array` to set the values.

Here is the code (without basemap as I do not have the shape file):

``````import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection

# some random numbers for demonstration
data = np.random.normal(0, 1, (100, 2))
value = np.random.normal(0, 1, 100)

polygons = [
Polygon([(0, 0), (0, 3), (-3, 3), (-3, 0)], closed=True),
Polygon([(0, 0), (0, -3), (-3, -3), (-3, 0)], closed=True),
Polygon([(0, 0), (0, 3), (3, 3), (3, 0)], closed=True),
Polygon([(0, 0), (0, -3), (3, -3), (3, 0)], closed=True),
]

poly_values = []
for poly in polygons:
mask = np.array([poly.contains_point(xy) for xy in data])

coll = PatchCollection(polygons, cmap='magma')
coll.set_array(np.array(poly_values))

fig, ax = plt.subplots()