我需要在多边形内创建海面温度(SST)数据的填充等高线图,但我不确定这样做的最佳方法 . 我有三个包含X,Y和SST数据的一维数组,我使用以下内容绘制以创建附图:
p=PatchCollection(mypatches,color='none', alpha=1.0,edgecolor="purple",linewidth=2.0)
levels=np.arange(SST.min(),SST.max(),0.2)
datamap=mymap.scatter(x,y,c=SST, s=55, vmin=-2,vmax=3,alpha=1.0)
我希望能够将这些数据绘制为在多边形边界(紫色线)内受约束(剪切)的填充轮廓(contourf而不是散射) . 非常感谢有关如何实现这一目标的建议 .
Update: 我最初尝试过griddata,但无法让它正常工作 . 但是,根据@eatHam提供的答案,我决定再试一次 . 当我选择方法'cubic'时,我无法让我的scipy griddata工作,因为它一直悬挂在网格上,但是当我切换到matplotlib.mlab.griddata并使用'linear'插值时它工作了 . 掩盖边界的建议提供了一个非常粗略而不是我想要的精确解决方案 .
我搜索了如何在matplotlib中剪辑轮廓的选项,我在@446352_找到了@pelson的答案 . 我尝试了暗示的建议解决方案:"The contour set itself does not have a set_clip_path method but you can iterate over each of the contour collections and set their respective clip paths" . 我的新的最终解决方案看起来像这样(见下图):
p=PatchCollection(mypatches,color='none', alpha=1.0,edgecolor="purple",linewidth=2.0)
levels=np.arange(SST.min(),SST.max(),0.2)
grid_x, grid_y = np.mgrid[x.min()-0.5*(x.min()):x.max()+0.5*(x.max()):200j,
y.min()-0.5*(y.min()):y.max()+0.5*(y.max()):200j]
grid_z = griddata(x,y,SST,grid_x,grid_y)
cs=mymap.contourf(grid_x, grid_y, grid_z)
for poly in mypatches:
for artist in ax.get_children():
artist.set_clip_path(poly)
ax.add_patch(poly)
mymap.drawcountries()
mymap.drawcoastlines()
mymap.fillcontinents(color='lightgrey',lake_color='none')
mymap.drawmapboundary(fill_color='none')
在推断北方的极端边缘方面,这种解决方案也可以特别改进 . 关于如何真正“填充”完整多边形的建议值得赞赏 . 我也想了解为什么mlab工作和scipy没有 .
1 回答
我会使用scipy.griddata插入数据 . 您可以将区域之外的区域(mypatches)设置为
np.nan
. 然后使用pyplot.contour绘制它 .编辑:在plt.contourf()调用中更改变量名称(是..(grid_z,grid_y,grid_z))