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

我需要在多边形内创建海面温度(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)

我希望能够将这些数据绘制为在多边形边界(紫色线)内受限(裁剪)的填充轮廓(轮廓线,而不是散点图)。 如何实现这一点的建议非常感谢。

在这里输入图像描述

更新:我最初尝试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')

这个解决方案也可以通过外推北方的极端边缘而得到特别的改进。 对如何真正“填充”完整多边形的建议表示赞赏。 我也想明白为什么mlab工作和scipy没有。

最终解决方案使用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()

在这里输入图像描述

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

链接地址: http://www.djcxy.com/p/74299.html

上一篇: Contour irregular data within polygon

下一篇: Android SIP application using Linphone