Tro*_*sen 7 python matplotlib matplotlib-basemap
我需要在多边形内创建海面温度(SST)数据的填充等高线图,但我不确定最好的方法.我有三个包含X,Y和SST数据的1D数组,我使用以下内容绘制以创建附图:
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)
Run Code Online (Sandbox Code Playgroud)
我希望能够绘制这些数据作为填充轮廓(contourf而不是散射)被约束(剪切)多边形边界内(紫线).非常感谢有关如何实现这一目标的建议.

更新:
我最初尝试过griddata,但无法使其正常工作.但是,根据@eatHam提供的答案,我决定再试一次.当我选择方法'立方'时,我无法让我的scipy griddata工作,因为它一直悬挂在网格上,但是当我切换到matplotlib.mlab.griddata并使用'线性'插值时它起作用.掩盖边界的建议提供了一个非常粗略而不是我想要的精确解决方案.

我搜索了如何在matplotlib中剪辑轮廓的选项,我在这个链接上找到了@pelson的答案.我尝试了暗示的建议解决方案:"轮廓集本身没有set_clip_path方法,但您可以迭代每个轮廓集合并设置它们各自的剪辑路径".我的新的最终解决方案看起来像这样(见下图):
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')
Run Code Online (Sandbox Code Playgroud)
在推断北方的极端边缘方面,这种解决方案也可以特别改进.关于如何真正"填充"完整多边形的建议值得赞赏.我也想了解为什么mlab工作和scipy没有.

我将使用scipy.griddata插入数据。您可以将您所在区域之外的区域 (mypatches) 设置为np.nan。然后使用pyplot.contour来绘制它。
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
def sst_data(x, y):
return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2
#replace with ...
x = np.random.rand(1000) #... your x
y = np.random.rand(1000) #... your y
sst = sst_data(x, y) #... your sst
# interpolate to a grid
grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j]
grid_z = griddata((x,y), sst, (grid_x, grid_y), method='cubic')
# mask out the area outside of your region
nr, nc = grid_z.shape
grid_z[-nr//3:, -nc//3:] = np.nan
plt.contourf(grid_x, grid_y, grid_z)
plt.show()
Run Code Online (Sandbox Code Playgroud)

编辑:更改了 plt.contourf() 调用中的变量名称(是 ..(grid_z, grid_y, grid_z))