ax.add_geometries无法加载shp文件

作者在撰写毕业论文时遇到cartopy包中shp文件在地图上不显示的问题,经排查发现是由于绘图范围与shp文件的投影范围不匹配。通过使用Arcgis的project工具将shp文件投影转换至地理坐标系,解决了这个问题。

最近在写毕业论文,上手练习一下cartopy包。

问题:

正常运行ax.add_geometries代码,但是shp文件在结果图中一直不显示。一开始还以为是投影有问题,代码中设置的是简易圆柱(Plate Carrée) 投影,但后面也尝试了其他投影,依然显示不了。

ax.add_geometries(Reader(shp_path).geometries(), ccrs.PlateCarree(), facecolor='none', edgecolor='k', linewidth=0.65)

运行结果如下:

问题发现:

原来是子图中的绘图范围与Shp的数值范围不匹配!

即:我之前提供的shp文件是投影过的,检查代码如下:

import geopandas as gpd
# 读取Shapefile
gdf = gpd.read_file(shp_path)
# 获取边界
bounds = gdf.total_bounds
print("Shapefile bounds:", bounds)
#结果: [11448677.0 3047834.8 11625463.8 3218060.9 ]

然而,我的绘图范围确是用经纬度表示的,检查代码如下:

xlim = ax.get_xlim()#这个ax是我子图的轴
ylim = ax.get_ylim()
print("Current map view limits:", xlim, ylim)
#结果:Current map view limits: (102.5, 105.0) (27.0, 29.5)

解决:

将shp文件投影更替为地理坐标系即可,我是用的Arcgis的project工具。然后,再检查shp文件的数值范围时,其范围就落入绘图范围中啦!

#同样的代码
import geopandas as gpd
# 读取Shapefile
gdf = gpd.read_file(shp_path)
# 获取边界
bounds = gdf.total_bounds
print("Shapefile bounds:", bounds)
#结果更新: [102.9 27.5 104.7 28.9]

绘图结果:

完结撒花!

import matplotlib matplotlib.use('Agg') # 必须放在 pyplot 之前 import numpy as np import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeature from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter import xarray as xr import cartopy.io.shapereader as shpreader # 设置中文字体 plt.rcParams['font.sans-serif'] = ['Times New Roman'] plt.rcParams['axes.unicode_minus'] = False # 打开 NetCDF 数据集 f = xr.open_dataset('D:\\wangnan\\2024sjxm\\shuju\\spei01new.nc') spei81_10 = f.spei.loc[f.time.dt.month.isin([8]), 35:38].loc['1991':'2020'] x1 = spei81_10.mean('time') # 8月(1990-2020)平均 # Shapefile 文件路径 shp_path = 'D:\\wangnan\\2024sjxm\\shuju\\hyx\\海原县.shp' # 替换为你的 Shapefile 路径 # 绘图函数 def clim_plot_with_shapefile(): fig = plt.figure(figsize=(6, 6), facecolor='w') ax = fig.add_axes([0.2, 0.2, 0.7, 0.7], projection=ccrs.PlateCarree(central_longitude=180)) ax.set_title(' Summer(1991-2020) Ave Spei', loc='left', fontsize=13) # 添加陆地掩膜 ax.add_feature(cfeature.LAND, zorder=1, facecolor='lightgray') ax.add_feature(cfeature.BORDERS, lw=0.25) ax.add_feature(cfeature.STATES, lw=0.25) # 设置绘图范围 ax.set_xlim([104, 107]) ax.set_ylim([35, 38]) # 设置坐标轴刻度 ax.set_xticks(np.arange(104, 107, 0.2), crs=ccrs.PlateCarree()) ax.set_yticks(np.arange(35, 38, 0.2), crs=ccrs.PlateCarree()) ax.xaxis.set_major_formatter(LongitudeFormatter()) ax.yaxis.set_major_formatter(LatitudeFormatter()) ax.tick_params(which='major', width=0.5, length=5) # 调整 lon 到 [-180, 180] 范围 x1_adjusted = x1.assign_coords(lon=(((x1.lon + 180) % 360) - 180)) # 使用 pcolormesh 替代 contourf m = ax.pcolormesh(x1_adjusted.lon, x1_adjusted.lat, x1_adjusted, cmap='seismic_r', vmin=-1.5, vmax=1.5, transform=ccrs.PlateCarree()) # 读取 Shapefile 文件 shape_feature = cfeature.ShapelyFeature( shpreader.Reader(shp_path).geometries(), ccrs.PlateCarree(), facecolor='none', # 无填充 edgecolor='black', # 黑色边界线 linewidth=1.0 # 线宽 ) ax.add_feature(shape_feature, zorder=2) # zorder 控制图层顺序 # 添加 colorbar cax = fig.add_axes([0.26, 0.1, 0.57, 0.017]) cb = fig.colorbar(m, cax=cax, orientation='horizontal', ticks=np.arange(-1.4, 1.4, 0.2)) cb.outline.set_linewidth(0.1) cb.ax.tick_params(length=0) return fig # 保存图像 clim_plot_with_shapefile() plt.savefig('qihoutai_with_haiyuan.png') plt.close()该代码出来的图被挤压成一条线并出现DownloadWarning: Downloading: https://naturalearth.s3.amazonaws.com/10m_physical/ne_10m_land.zip warnings.warn(f'Downloading: {url}', DownloadWarning)怎么解决
09-10
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值