如何在Python GeoDataFrame中为点位添加带箭头的标签?
带自动避重叠标签箭头的地图可视化实现
可以实现自动调整标签位置避免重叠的需求,我们可以借助adjustText库来完成这项功能,同时用Matplotlib的箭头连接标签和点位。以下是修改后的完整代码:
import pandas as pd import matplotlib.pyplot as plt from shapely.geometry import Point import geopandas as gpd from geopandas import GeoDataFrame import json from adjustText import adjust_text # 需要先安装:pip install adjustText # 创建经纬度数据框 def createLatitudeLongitudeDataFrame(inputJsonFolder, inputJsonFilename): data = json.load(open(inputJsonFolder + "\\" + inputJsonFilename)) latitudes = [] longitudes = [] for location in data["locations"]: latitudes.append(location["coordinates"]["latitude"]) longitudes.append(location["coordinates"]["longitude"]) data_tuples = list(zip(latitudes, longitudes)) df = pd.DataFrame(data_tuples, columns=["Latitudes", "Longitudes"]) # 添加标签列,生成A、B、C...序列 df['Label'] = [chr(ord('A') + i) for i in range(len(df))] return df # 创建带标签箭头的位置地图 def createMapOfLocations(df): geometry = [Point(yx) for yx in zip(df['Longitudes'], df['Latitudes'])] gdf = GeoDataFrame(df, geometry=geometry) # 加载基础地图 world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) ax = world.plot(figsize=(10, 6)) gdf.plot(ax=ax, marker='o', color='red', markersize=15) # 准备标签文本 texts = [] for idx, row in df.iterrows(): text = ax.text(row['Longitudes'], row['Latitudes'], row['Label'], fontsize=12, fontweight='bold') texts.append(text) # 自动调整标签位置+添加连接箭头 adjust_text(texts, x=df['Longitudes'], y=df['Latitudes'], arrowprops=dict(arrowstyle='->', color='black', lw=1), expand_points=(1.2, 1.2), # 控制标签与点位的基础间距 force_text=(0.5, 1) # 调整标签位置的力度,数值越大调整幅度越强 ) plt.show() def main(): inputJsonFolder = "\\inputFolder" inputJsonFilename = "testing.json" df = createLatitudeLongitudeDataFrame(inputJsonFolder, inputJsonFilename) createMapOfLocations(df) main()
关键说明:
- 依赖安装:先执行
pip install adjustText安装自动调整标签的库。 - 标签生成:自动为每个点位分配A、B、C...的序列标签,也可以根据需求替换为自定义名称。
- 自动避重叠:
adjust_text函数会自动计算标签的最优摆放位置,避免相互遮挡,同时通过arrowprops配置箭头样式,确保标签和点位的对应关系清晰。 - 参数微调:可以通过
expand_points、force_text等参数,根据点位的密集程度调整标签间距和调整力度,适配不同的可视化场景。
内容的提问来源于stack exchange,提问作者graphtheory123
相关产品推荐
相关产品推荐

