Python Cartopy地图,国家/地区以外的剪贴区域(多边形) [英] Python cartopy map, clip area outside country (polygon)

查看:698
本文介绍了Python Cartopy地图,国家/地区以外的剪贴区域(多边形)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用来自NaturalEarth的国家边界创建了Stamen地形图。
现在,我想从国家边界之外删除所有数据(在这种情况下为地形)。
我该怎么做?



我的示例在瑞士内外都可见:

 从cartopy.io导入shapereader 
导入cartopy.io.img_tiles作为cimgt
导入cartopy.crs作为ccrs
导入geopandas
导入matplotlib.pyplot as plt


分辨率='10m'
类别='文化'
名称='admin_0_countries'

shpfilename = shapereader.natural_earth(分辨率,类别,名称)

df = geopandas.read_file(shpfilename)

poly = [df.loc [df ['ADMIN'] ==' Switzerland'] ['geometry']。values [0]]

stamen_terrain = cimgt.Stamen('terrain-background')

图= plt.figure(figsize = (8,6))

ax = fig.add_subplot(1、1、1投影= stamen_terrain.crs)
ax.add_geometries(poly,crs = ccrs.PlateCarree(), facecolor ='none',edgecolor ='r')
exts = [poly [0] .bounds [0],poly [0] .bounds [2],poly [0] .bounds [1],poly [0] .bounds [3]]
ax.set_extent(exts,crs = ccrs.G eodetic())

ax.add_image(stamen_terrain,8)
图.tight_layout()
plt.show()



我如何仅显示



试图在这个方向上玩,但到目前为止没有成功:


和掩码:



I create a Stamen terrain map with the country border from NaturalEarth. Now I want to remove all the data (terrain in this case) from outside the country border. How would I do that?

My example with the terrain visible inside and outside of Switzerland:

from cartopy.io import shapereader
import cartopy.io.img_tiles as cimgt
import cartopy.crs as ccrs
import geopandas
import matplotlib.pyplot as plt


resolution = '10m'
category = 'cultural'
name = 'admin_0_countries'

shpfilename = shapereader.natural_earth(resolution, category, name)

df = geopandas.read_file(shpfilename)

poly = [df.loc[df['ADMIN'] == 'Switzerland']['geometry'].values[0]]

stamen_terrain = cimgt.Stamen('terrain-background')

fig = plt.figure(figsize=(8,6))

ax = fig.add_subplot(1, 1, 1, projection=stamen_terrain.crs)
ax.add_geometries(poly, crs=ccrs.PlateCarree(), facecolor='none', edgecolor='r')
exts = [poly[0].bounds[0], poly[0].bounds[2], poly[0].bounds[1], poly[0].bounds[3]]
ax.set_extent(exts, crs=ccrs.Geodetic())

ax.add_image(stamen_terrain, 8)
fig.tight_layout()
plt.show()

How can I show only the terrain within the border, and the rest outside as white/transparent?

Tried to play with this direction, but without success so far: https://scitools.org.uk/cartopy/docs/latest/gallery/logo.html

解决方案

You need a mask to hide the un-wanted part of the image. Here is a runnable code that demonstrates all the steps to get the intended plot.

from shapely.geometry import Polygon
from cartopy.io import shapereader
import cartopy.io.img_tiles as cimgt
import cartopy.crs as ccrs
import geopandas
import matplotlib.pyplot as plt

def rect_from_bound(xmin, xmax, ymin, ymax):
    """Returns list of (x,y)'s for a rectangle"""
    xs = [xmax, xmin, xmin, xmax, xmax]
    ys = [ymax, ymax, ymin, ymin, ymax]
    return [(x, y) for x, y in zip(xs, ys)]

# request data for use by geopandas
resolution = '10m'
category = 'cultural'
name = 'admin_0_countries'

shpfilename = shapereader.natural_earth(resolution, category, name)
df = geopandas.read_file(shpfilename)

# get geometry of a country
poly = [df.loc[df['ADMIN'] == 'Switzerland']['geometry'].values[0]]

stamen_terrain = cimgt.Stamen('terrain-background')

# projections that involved
st_proj = stamen_terrain.crs  #projection used by Stamen images
ll_proj = ccrs.PlateCarree()  #CRS for raw long/lat

# create fig and axes using intended projection
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(1, 1, 1, projection=st_proj)
ax.add_geometries(poly, crs=ll_proj, facecolor='none', edgecolor='black')

pad1 = .1  #padding, degrees unit
exts = [poly[0].bounds[0] - pad1, poly[0].bounds[2] + pad1, poly[0].bounds[1] - pad1, poly[0].bounds[3] + pad1];
ax.set_extent(exts, crs=ll_proj)

# make a mask polygon by polygon's difference operation
# base polygon is a rectangle, another polygon is simplified switzerland
msk = Polygon(rect_from_bound(*exts)).difference( poly[0].simplify(0.01) )
msk_stm  = st_proj.project_geometry (msk, ll_proj)  # project geometry to the projection used by stamen

# get and plot Stamen images
ax.add_image(stamen_terrain, 8) # this requests image, and plot

# plot the mask using semi-transparency (alpha=0.65) on the masked-out portion
ax.add_geometries( msk_stm, st_proj, zorder=12, facecolor='white', edgecolor='none', alpha=0.65)

ax.gridlines(draw_labels=True)

plt.show()

The resulting plot:

and the mask:

这篇关于Python Cartopy地图,国家/地区以外的剪贴区域(多边形)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆