gpt4 book ai didi

python - 多边形内的轮廓不规则数据

转载 作者:太空狗 更新时间:2023-10-29 21:53:13 24 4
gpt4 key购买 nike

我需要在多边形内创建海面温度 (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 而不是散点图),这些轮廓在多边形边界(紫色线)内受到约束(剪裁)。非常感谢有关如何实现这一目标的建议。

enter image description here

更新:我最初尝试过 griddata,但无法使其正常工作。但是,根据@eatHam 提供的答案,我决定再试一次。我无法让我的 scipy griddata 工作,因为它在选择方法 'cubic' 时一直卡在网格上,但是当我切换到 matplotlib.mlab.griddata 并使用 'linear' 插值时它起作用了。屏蔽边界的建议提供了一个非常粗略的解决方案,并不像我希望的那样精确。 Image showing the solution using masked clipping

我搜索了有关如何在 matplotlib 中裁剪轮廓的选项,并在这个 link 找到了@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')

这个解决方案还可以改进,特别是在推断北方的极端边缘方面。感谢有关如何真正“填充”完整多边形的建议。我也想了解为什么 mlab 有效而 scipy 无效。

Final solution showing clipped contours using set_clip_path

最佳答案

我会使用 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()

enter image description here

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

关于python - 多边形内的轮廓不规则数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18772710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com