Skip to main content
 首页 » 编程设计

python之绘制由散点数据决定颜色的Shapefile

2025年05月04日15emanlee

我的问题

用 shapefile 绘制热图

1.简介

  • 一堆shapefile代表行政边界
  • 一个 pandas.Dataframe 包含一些具有(经度,纬度,值)的点

代码在这里:

 map = Basemap(llcrnrlon=xc1,llcrnrlat=yc1,urcrnrlon=xc2,urcrnrlat=yc2) 
 ##Assuming "shape.shp" is my shapefile 
 map.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 Dataframe 
 pt_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) 

图片在这里:

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

2。我的目标

在上图中,每个shapefile的颜色都是基于预定义的colormap。

  • 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

添加--2015-01-11

感谢@MaxNoe 的回答。

学习了你的代码,但还是有问题。
这是我的代码和图片:

 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.

请您参考如下方法:

  • 您可以使用 Polygon.contains_point 检查点是否在其中。

  • 我使用此函数创建一个 bool 掩码来寻址该多边形内的点,并使用 .sum() 获取此多边形的值。

  • 然后我使用 PatchCollection.set_array 设置值。

这是代码(没有 basemap ,因为我没有形状文件):

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]) 
    poly_values.append(value[mask].sum()) 
 
 
coll = PatchCollection(polygons, cmap='magma') 
coll.set_array(np.array(poly_values)) 
 
fig, ax = plt.subplots() 
ax.add_collection(coll) 
points = ax.scatter(data[:, 0], data[:, 1], c=value, cmap='viridis', linewidth=0) 
fig.colorbar(coll, label='polygons') 
fig.colorbar(points, label='points') 
plt.show() 

结果: