如何使用 Cartopy 在两个坐标之间绘制直线
在我们之前的文章使用 Cartopy 的最小测地线示例和如何在 Cartopy 中增加测地线分辨率/精度/平滑度中,我们展示了如何在地图上创建测地线。虽然测地线被定义为地球表面上最短的线,但它不是地图投影上的直线。
为了绘制测地线我们使用:
plot_line_cartopy.py
plt.plot([lon1, lon2], [lat1, lat2], transform=ccrs.Geodetic())为了绘制直线,我们需要使用与创建地图时相同的投影而不是 transform=ccrs.Geodetic().
例如,如果我们使用以下命令创建地图
create_axes.py
plt.axes(projection=ccrs.PlateCarree())我们需要使用 transform=ccrs.PlateCarree() 绘制线
plot_line_platecarree.py
plt.plot([lon1, lon2], [lat1, lat2], transform=ccrs.PlateCarree())为了避免错误,我强烈建议仅使用投影的一个实例并将其分配给公共变量,例如:
cartopy_example.py
proj = ccrs.PlateCarree()
ax = plt.axes(projection=proj)
plt.plot([-75, 77.23], [43, 28.61], transform=proj)注意由于目前我不了解的原因,这目前仅适用于某些投影。使用 ccrs.PlateCarree() 和 ccrs.Miller() 有效,但使用 ccrs.Mollweide() 无效!
完整示例
此代码重现上面显示的图像:
cartopy_full_example.py
import cartopy.crs as ccrs
import cartopy.feature as cf
from matplotlib import pyplot as plt
proj = ccrs.PlateCarree()
ax = plt.axes(projection=proj)
ax.stock_img()
ax.add_feature(cf.BORDERS)
# 在两点之间添加直线
# 格式:plot([lon1, lon2], [lat1, lat2])
plt.plot([-75, 77.23], [43, 28.61], linestyle='--',
color='blue', linewidth=8,
transform=proj)
# 使图更大
plt.gcf().set_size_inches(20, 10)
# 将图保存为 SVG
plt.savefig("Cartopy-Straight-Line-PlateCarree.svg")If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow