首页 文章

如何使用设置剪裁路径为Basemap多边形

提问于
浏览
6

我想使用imshow(例如)在一个国家的边界内显示一些数据(为了我的例子,我选择了美国)下面的简单例子说明了我想要的:

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)
im = ax.imshow(data)
poly = RegularPolygon([ 0.5,  0.5], 6, 0.4, fc='none', 
                      ec='k', transform=ax.transAxes)
im.set_clip_path(poly)
ax.add_patch(poly)
ax.axis('off')
plt.show()

结果是:

enter image description here

现在我想这样做但不是简单的多边形,我想使用美国的复杂形状 . 我已经创建了一些包含在“Z”数组中的示例数据,如下面的代码所示 . 我希望使用colourmap显示这些数据,但仅限于美国大陆的边界 .

到目前为止,我已尝试过以下内容 . 我从"nationp010g.shp.tar.gz"中获得了here的形状文件,并使用python中的Basemap模块绘制了美国 . 请注意,这是我找到的唯一方法,它使我能够获得我需要的区域的多边形 . 如果有其他方法,我也会对它们感兴趣 . 然后我创建了一个名为"mainpoly"的多边形,它几乎是我想要用蓝色着色的多边形:

enter image description here

请注意,只有一个物体被着色,所有其他不相交的多边形保持白色:

enter image description here

因此,蓝色区域几乎是我想要的,请注意加拿大附近有不必要的边界线,因为边界实际上穿过了一些湖泊,但这是一个小问题 . 真正的问题是,为什么我的imshow数据不在美国境内显示?比较我的第一个和第二个示例代码,我无法理解为什么我在第二个示例中没有得到修剪的imshow,就像我在第一个示例中所做的那样 . 在理解我所缺少的内容时,我们将不胜感激 .

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

# Lambert Conformal map of lower 48 states.
m = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
            projection='lcc',lat_1=33,lat_2=45,lon_0=-95)


shp_info = m.readshapefile('nationp010g/nationp010g', 'borders', drawbounds=True) # draw     country boundaries.

for nshape,seg in enumerate(m.borders):
    if nshape == 1873: #This nshape denotes the large continental body of the USA, which we want
        mainseg = seg
        mainpoly =  Polygon(mainseg,facecolor='blue',edgecolor='k')



nx, ny = 10, 10
lons, lats = m.makegrid(nx, ny) # get lat/lons of ny by nx evenly space grid.
x, y = m(lons, lats) # compute map proj coordinates.

Z = np.zeros((nx,ny))
Z[:] = np.NAN

for i in np.arange(len(x)):
    for j in np.arange(len(y)):
        Z[i,j] = x[0,i] 

ax = plt.gca()
im = ax.imshow(Z, cmap = plt.get_cmap('coolwarm') )
im.set_clip_path(mainpoly)
ax.add_patch(mainpoly)
plt.show()

更新

我意识到这一行

ax.add_patch(mainpoly)

甚至没有将多边形形状添加到绘图中 . 我没有正确使用它吗?据我所知,使用Polygon()方法正确计算了mainpoly . 我检查了坐标输入是否明智:

plt.plot(mainseg[:,0], mainseg[:,1] ,'.')

这使

enter image description here

1 回答

  • 3

    我已经考虑了这个问题很久了 .
    我发现NCL语言具有屏蔽某些边界外的数据的功能 .
    这是一个例子:

    http://i5.tietuku.com/bdb1a6c007b82645.png

    contourf图仅显示在中国境内 . 单击here获取代码 .

    我知道python有一个名为PyNCL的包,它支持Python框架中的所有NCL代码 .
    但我真的想用底图来绘制这种图形 . 如果您已经弄清楚了,请在互联网上发布 . 我将在第一时间学习 .

    谢谢!

    添加2016-01-16

    在某种程度上,我已经弄明白了 .
    这是我的想法和代码,它的灵感来自我今天提出的这个问题 .

    我的方法:
    1.将有趣区域(如美国)的shapefile变为shapely.polygon .
    2.测试多边形内/外的每个值点 .
    3.如果值点在研究区域之外,则将其掩盖为np.nan

    简介*多边形xxx是中国ESRI shapefile格式的城市 . * fiona,造型包装在这里使用 .

    # generate the shapely.polygon
    shape = fiona.open("xxx.shp")
    pol = shape.next()
    geom = shape(pol['geometry'])
    poly_data = pol["geometry"]["coordinates"][0]
    poly = Polygon(poly_data)
    

    它显示如下:

    http://i4.tietuku.com/2012307faec02634.png

    ### test the value point 
    ### generate the grid network which represented by the grid midpoints.
    lon_med  = np.linspace((xi[0:2].mean()),(xi[-2:].mean()),len(x_grid))
    lat_med  = np.linspace((yi[0:2].mean()),(yi[-2:].mean()),len(y_grid))
    
    value_test_mean = dsu.mean(axis = 0)
    value_mask =  np.zeros(len(lon_med)*len(lat_med)).reshape(len(lat_med),len(lon_med))
    for i in range(0,len(lat_med),1):
        for j in range(0,len(lon_med),1):
            points = np.array([lon_med[j],lat_med[i]])
            mask = np.array([poly.contains(Point(points[0], points[1]))])
            if mask == False:
                value_mask[i,j] = np.nan
            if mask == True:
                value_mask[i,j] = value_test_mean[i,j]
    
    
    # Mask the np.nan value 
    Z_mask = np.ma.masked_where(np.isnan(so2_mask),so2_mask)
    
    # plot!
    fig=plt.figure(figsize=(6,4))
    ax=plt.subplot()
    
    map = Basemap(llcrnrlon=x_map1,llcrnrlat=y_map1,urcrnrlon=x_map2,urcrnrlat=y_map2)
    map.drawparallels(np.arange(y_map1+0.1035,y_map2,0.2),labels=  [1,0,0,1],size=14,linewidth=0,color= '#FFFFFF')
    lon_grid  = np.linspace(x_map1,x_map2,len(x_grid))
    lat_grid  = np.linspace(y_map1,y_map2,len(y_grid))
    xx,yy = np.meshgrid(lon_grid,lat_grid)
    pcol =plt.pcolor(xx,yy,Z_mask,cmap = plt.cm.Spectral_r ,alpha =0.75,zorder =2)
    

    结果

    http://i4.tietuku.com/c6620c5b6730a5f0.png

    http://i4.tietuku.com/a22ad484fee627b9.png

    原始结果

    http://i4.tietuku.com/011584fbc36222c9.png

相关问题