Skip to main content
 首页 » 编程设计

python之多个形状内的 basemap 轮廓

2024年09月03日24zfyouxi

我试图仅在 shapefile 中包含的城镇范围内在 map 上绘制插值天气数据。以下是带有导入 shapefile 的 basemap 上未裁剪的 contourf: Contourf overlaid on Basemap with Shapefile

我试过像这样遍历轮廓集合来裁剪轮廓集合:

m.readshapefile('data/grense', 'grense',zorder=10,linewidth=1,  
drawbounds=True) 
 
patches   = [] 
for info, shape in zip(m.grense_info, m.grense): 
   patches.append( Polygon(np.array(shape), linestyle=':', fill=False) ) 
 
for poly in patches: 
   for collection in cs.collections: 
      collection.set_clip_path(poly) 

这显然将等高线限制在一个多边形内,即一个城镇,如下所示: Contourf clipped to one ploygon

是否可以创建一个轮廓集合的集合,然后我可以使用 ax.add_collection(new_contour_collection) 添加这些集合?类似的东西:

for poly in patches: 
   for collection in cs.collections: 
     contour_collection.append(collection) 
ax.add_collection(contour_collection) 

或者我可以从 Patchcollection 创建单个路径,然后使用 collection.set_clip_patch(patches) 剪辑每个轮廓集合吗?

请您参考如下方法:

正在关注 swatchai的建议和Thomas Kühn之前的回答here ,我设法解决了我的问题,在这里看到 ,

通过执行以下操作:

#Combine shapefile shape object (m.grense) with map edges 
##limits of the map: 
x0,x1 = ax.get_xlim() 
y0,y1 = ax.get_ylim() 
map_edges = np.array([[x0,y0],[x1,y0],[x1,y1],[x0,y1]]) 
 
polys = [map_edges] + m.grense 
 
codes = [ 
    [Path.MOVETO] + [Path.LINETO for p in p[1:]] 
    for p in polys 
] 
polys_lin = [v for p in polys for v in p] 
codes_lin = [c for cs in codes for c in cs] 
path = Path(polys_lin, codes_lin) 
 
#Important - Set Zorder greater than Contour and less than Map  
borders 
patch = PathPatch(path,facecolor='white', lw=0, zorder =2) 
 
##masking the data: 
ax.add_patch(patch)