使用投影绘制geoplot地理图时点标注不显示问题咨询
标注不显示问题解决方案
问题原因
- 绘图轴使用了自定义的AlbersEqualArea投影坐标系,但
plt.annotate传入的是原始WGS84坐标系的经纬度值,二者坐标系统不匹配,导致标注被绘制到了画布可视区域外 - 传入的
xy参数坐标顺序错误,纬度在前、经度在后,进一步加剧了坐标偏移 - 未设置标注的
zorder,可能被层级更高的点图层遮挡
修复方法
以下两种方案二选一即可:
方案1:使用transform参数自动坐标转换(更简便)
直接指定标注输入坐标的参考系,让matplotlib自动完成投影转换,无需手动转坐标系:
import geopandas as gpd import geoplot as gplt import matplotlib.pyplot as plt # 定义投影 proj = gplt.crs.AlbersEqualArea() fig, ax = plt.subplots(figsize=(10, 10), subplot_kw={'projection': proj}) # 构建GeoDataFrame,指定原始WGS84坐标系 gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.longitude, df.latitude), crs="EPSG:4326") gplt.pointplot(gdf, hue='size', s=15, ax=ax, cmap=palette, legend=True, zorder=10) # 标注逻辑修改 for idx, row in gdf.iterrows(): ax.annotate( text=row['Name'], # 高版本matplotlib用text参数替代s参数 xy=(row['longitude'], row['latitude']), # 经度在前,纬度在后 xycoords=ax.get_transform('EPSG:4326'), # 指定输入坐标为WGS84坐标系 fontsize=8, zorder=11, # 层级高于点图层,避免被遮挡 xytext=(3, 3), # 可选:标注相对点的偏移量,避免重叠 textcoords='offset points' ) plt.show()
方案2:手动将GeoDataFrame转为轴的投影坐标系
先把矢量数据转成和绘图轴一致的投影,直接取投影后的平面坐标标注:
import geopandas as gpd import geoplot as gplt import matplotlib.pyplot as plt proj = gplt.crs.AlbersEqualArea() fig, ax = plt.subplots(figsize=(10, 10), subplot_kw={'projection': proj}) gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.longitude, df.latitude), crs="EPSG:4326") # 转成和轴一致的投影 gdf_proj = gdf.to_crs(proj) gplt.pointplot(gdf, hue='size', s=15, ax=ax, cmap=palette, legend=True, zorder=10) for idx, row in gdf_proj.iterrows(): ax.annotate( text=row['Name'], xy=(row.geometry.x, row.geometry.y), # 直接取投影后的平面坐标 fontsize=8, zorder=11, xytext=(3, 3), textcoords='offset points' ) plt.show()
内容的提问来源于stack exchange,提问作者Elias_sweden
相关产品推荐
相关产品推荐

