

新闻资讯
技术学院使用cartopy在Python中绘制地图标注线,首先创建带投影的图形,添加海岸线和国界等地理特征,设置中国区域范围,通过ax.plot()连接北京与上海坐标并设置样式,利用ax.text()在中点添加“航线”文字标注及城市名,关键需指定transform=ccrs.PlateCarree()确保经纬度正确投影,最终显示带标题的地图;若需交互式效果可选用folium库生成网页地图。
在Python中绘制地图上的标注线,常用的方法是结合地理可视化库如 matplotlib、basemap(已不再维护但仍有使用)、cartopy 或更现代的 folium 和 geopandas。下面以 matplotlib + cartopy 为例,展示如何在地图上画一条带标注的线。
pip install matplotlib cartopy numpy
下面是一个完整示例,在地图上从北京到上海画一条线,并标注“航线”:
import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeature # 创建图形和轴,使用 PlateCarree 投影 fig = plt.figure(figsize=(10, 6)) ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree()) # 添加地图细节 ax.add_feature(cfeature.COASTLINE) ax.add_feature(cfeature.BORDERS, linestyle=':') ax.add_feature(cfeature.LAND, facecolor='lightgray') ax.add_feature(cfeature.OCEAN, facecolor='lightblue') # 设置地图范围(中国区域) ax.set_extent([70, 140, 15, 55], crs=ccrs.PlateCarree()) # 定义两个城市的坐标(经度, 纬度) beijing = (116.4074, 39.9042) shanghai = (121.4737, 31.2304) # 绘制连接两点的线 ax.plot([beijing[0], shanghai[0]], [beijing[1], shanghai[1]], color='red', linewidth=2, marker='o', transform=ccrs.PlateCarree()) # 添加标注 mid_lon = (beijing[0] + shanghai[0]) / 2 mid_lat = (beijing[1] + shanghai[1]) / 2 ax.text(mid_lon, mid_lat, '航线', transform=ccrs.PlateCarree(), fontsize=12, color='darkblue', weight='bold', ha='center', va='center', backgroundcolor='white') # 添加城市标签 ax.text(beijing[0], beijing[1], '北京', transform=ccrs.PlateCarree(), fontsize=10, ha='right', va='bottom') ax.text(shanghai[0], shanghai[1], '上海', transform=ccrs.PlateCarree(), fontsize=10, ha='left', va='bottom') # 显示图 plt.title("地图上的标注线示例") plt.show()
transform=ccrs.PlateCarree():非常重要,它告诉 matplotlib 这些坐标是经纬度,避免投影错误。
ax.plot():用于画线,传入两个点的经度列表和纬度列表。
ax.text():在指定位置添加文字标注,可设置字体、颜色、背景等增强可读性。
如果你想要交互式地图,可以用 folium:
```python import foliumm = folium.Map(location=[35, 105], zoom_start=5)
folium.PolyLine( locations=[[39.9042, 116.4074], [31.2304, 121.4737]], color="red", weight=2.5, opacity=1 ).add_to(m)
folium.Marker( [35.5, 118.9], popup="航线", icon=folium.Icon(color="purple") ).add_to(m)
m.save("map_with_line.html")
基本上就这些。根据需求选择静态图还是交互图,cartopy 适合科研绘图,folium 适合网页展示。