如何防止 Matplotlib 地图注释中的重叠标签?

How to prevent overlapping labels in annotation in Matplotlib map?

我试图防止下面美国东北部地图中的标签重叠。我曾尝试为该地区的某些州打开和关闭标签,但肯定有更好的方法。下面是我的代码和输出。

csv = pd.read_csv(r'C:\Downloads\Data.csv')
sf = r'C:\Downloads\s_11au16\s_11au16.shp'
US = gpd.read_file(sf)

#Merge them
data = gpd.GeoDataFrame(csv.merge(US))

#set projection
data = data.to_crs(epsg=6923)

#set up basemap
ax = data.plot(figsize = (12,8), column="soil_data", cmap="Greens", edgecolor='black', linewidth=.5, vmin=0, vmax=70, 
               missing_kwds={"color": "white", "edgecolor": "k", "label": "none"})
ax.set_title("Example", fontsize=18, fontweight='bold')
ax.set_axis_off()


#annotate data
label = data.dropna(subset='soil_data')
label.apply(lambda x: ax.annotate(text=int(x['soil_data']), xy=x.geometry.centroid.coords[0], color="black", 
                                  ha='center', fontsize=14, path_effects=[pe.withStroke(linewidth=3, 
                                                                                        foreground="white")]), axis=1)

显然,没有你的数据我无法测试它,但如果你愿意用 adjustText 再试一次,你可以尝试用类似的东西替换你的 label.apply(...)

texts = []
for i, row in label.iterrows(): 
  texts.append(ax.annotate(text=int(row['soil_data']), xy=row.geometry.centroid.coords[0], color="black", 
                                  ha='center', fontsize=14, path_effects=[pe.withStroke(linewidth=3, 
                                                                                        foreground="white")]))

adjust_text(texts)

我不知道 adjust_text 如何处理注释,所以如果这不起作用,您可以尝试将其转换为 plt.text

(matplotlib class Annotation inherits from the Text class)