Plot only on continent in matplotlib

前端 未结 5 770
清歌不尽
清歌不尽 2020-11-27 07:13

I am drawing a map using basemap from matplotlib. The data are spreaded all over the world, but I just want to retain all the data on the continent and drop those on the oce

5条回答
  •  死守一世寂寞
    2020-11-27 07:54

    The simplest way is to use basemap's maskoceans.

    If for each lat, lon you have a data and you want to use contours: After meshgrid and interpolation:

    from scipy.interpolate import griddata as gd
    from mpl_toolkits.basemap import Basemap, cm, maskoceans
    xi, yi = np.meshgrid(xi, yi)
    zi = gd((mlon, mlat),
                scores,
                (xi, yi),
                method=grid_interpolation_method)
    #mask points on ocean
    data = maskoceans(xi, yi, zi)
    con = m.contourf(xi, yi, data, cmap=cm.GMT_red2green)
    #note instead of zi we have data now.
    

    Update (much faster than in_land or in_polygon solutions):

    If for each lat, lon you don't have any data, and you just want to scatter the points only over land:

    x, y = m(lons, lats)
    samples = len(lons)
    ocean = maskoceans(lons, lats, datain=np.arange(samples),
                       resolution='i')
    ocean_samples = np.ma.count_masked(ocean)
    print('{0} of {1} points in ocean'.format(ocean_samples, samples))
    m.scatter(x[~ocean.mask], y[~ocean.mask], marker='.', color=colors[~ocean.mask], s=1)
    m.drawcountries()
    m.drawcoastlines(linewidth=0.7)
    plt.savefig('a.png')
    

提交回复
热议问题