从basemap迁移至cartopy绘制shapefile仅显示中间点问题求助
问题诱因
- 坐标系参数传错:定义
ShapelyFeature时,第二个参数需要传入的是shapefile原始数据对应的坐标系,而非绘图所用的墨卡托投影。常规行政区划shapefile默认使用WGS84地理坐标系(单位为十进制度),错误传入墨卡托投影(单位为米)后,相当于把数值只有11.5、103104的经纬度数值直接当成米级坐标处理,在墨卡托的全球坐标体系下就会缩成画布中心的极小点。 - 未指定地图显示范围:Cartopy默认显示范围为全球,即使坐标系修正后如果不缩小显示范围到新加坡所在区域,也无法正常显示目标内容。
- 代码缺失
matplotlib.pyplot导入依赖,直接运行会报错。
修正方案
可参考下方修正后的代码运行:
import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.io.shapereader as shpreader from cartopy.feature import ShapelyFeature # 定义地图范围 lllat=1.1497 urlat=1.5133 lllon=103.5822 urlon=104.1579 # 初始化墨卡托投影画布 proj = ccrs.Mercator() ax = plt.axes(projection=proj) plt.gcf().set_size_inches(20, 10) # 读取shapefile,传入原始数据对应的WGS84坐标系 reader = shpreader.Reader("singapore_shapefile") shape_feature = ShapelyFeature(reader.geometries(), ccrs.PlateCarree(), facecolor="w", edgecolor='black', lw=1) ax.add_feature(shape_feature) # 设置显示范围,指定传入的范围值为WGS84经纬度坐标 ax.set_extent([lllon, urlon, lllat, urlat], crs=ccrs.PlateCarree()) plt.savefig("test.png")
内容的提问来源于stack exchange,提问作者Wboy
相关产品推荐
相关产品推荐

