首页 文章

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

提问于
浏览
7

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

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

我搜索了如何在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没有 .

Final solution showing clipped contours using set_clip_path

1 回答

  • 4

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

相关问题