首页 文章

如何在Basemap上隐藏特定区域的轮廓线/数据

提问于
浏览
2

我正在处理一些气象数据以在底图上绘制轮廓线 . 我之前完成的完整工作示例代码是How to remove/omit smaller contour lines using matplotlib . 一切正常,我不会抱怨轮廓图 . 但是有一种特殊情况,我必须隐藏Basemap上特定区域(不规则lat和lon)上的所有轮廓线 .

我能想到的唯一可能的解决方案是在所需区域上绘制一条ploygon线,并填充与Basemap相同的颜色 . 经过大量搜索,我发现此链接How to draw rectangles on a Basemap(下面的代码)

from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon

def draw_screen_poly( lats, lons, m):
    x, y = m( lons, lats )
    xy = zip(x,y)
    poly = Polygon( xy, facecolor='red', alpha=0.4 )
    plt.gca().add_patch(poly)

lats = [ -30, 30, 30, -30 ]
lons = [ -50, -50, 50, 50 ]

m = Basemap(projection='sinu',lon_0=0)
m.drawcoastlines()
m.drawmapboundary()
draw_screen_poly( lats, lons, m )

plt.show()

它似乎部分工作 . 但是,我想绘制一个不规则的区域 .

任何解决方案表示赞赏

Edit: 1

我已经明白问题所在 . 似乎在多边形区域内填充的任何颜色(facecolor)都不会使其隐藏在下面的任何内容中 . 无论是否使用 alpha 值,它始终只是透明的 . 为了说明这个问题,我裁剪了包含所有三个区域的图像,即 . 轮廓,底图区域和多边形区域 . 多边形区域填充红色,但正如您所见,轮廓线始终可见 . 我在上面的代码中使用的特定行是: -

poly = Polygon(xy, facecolor='red', edgecolor='b')

因此问题不在于上面的代码 . 这似乎是多边形填充的问题 . 但仍无法解决这个问题 . 生成的图像(裁剪图像)低于( See my 2nd edit below the attached image ): -

enter image description here

Edit 2: 从这个有类似要求的http://matplotlib.1069221.n5.nabble.com/Clipping-a-plot-inside-a-polygon-td41950.html中获取线索,我能够删除一些数据 . 但是,删除的数据仅来自多边形区域之外而不是内部 . 以下是我从中获取线索的代码: -

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import RegularPolygon

data = np.arange(100).reshape(10, 10)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.contourf(data)
poly = RegularPolygon([ 0.5,  0.5], 6, 0.4, fc='none', 
                      ec='k', transform=ax.transAxes)
for artist in ax.get_children():
    artist.set_clip_path(poly)

现在我的问题是用什么命令来删除多边形区域内的数据?

1 回答

  • 2

    没有注意到有人对此提出索赔,所以我可能只是提出已提出的解决方案here . 您可以修改zorder来隐藏多边形后面的东西:

    import matplotlib
    import matplotlib.mlab as mlab
    import matplotlib.pyplot as plt
    
    matplotlib.rcParams['xtick.direction'] = 'out'
    matplotlib.rcParams['ytick.direction'] = 'out'
    
    delta = 0.025
    x = np.arange(-3.0, 3.0, delta)
    y = np.arange(-2.0, 2.0, delta)
    X, Y = np.meshgrid(x, y)
    Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
    Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
    # difference of Gaussians
    Z = 10.0 * (Z2 - Z1)
    
    
    # Create a simple contour plot with labels using default colors.  The
    # inline argument to clabel will control whether the labels are draw
    # over the line segments of the contour, removing the lines beneath
    # the label
    fig = plt.figure()
    ax = fig.add_subplot(111)
    CS = plt.contour(X, Y, Z,zorder=3)
    plt.clabel(CS, inline=1, fontsize=10)
    plt.title('Simplest default with labels')
    
    rect1 = matplotlib.patches.Rectangle((0,0), 2, 1, color='white',zorder=5)
    
    ax.add_patch(rect1)
    
    plt.show()
    

    ,结果是:

    Hiding contour line with polygon

相关问题