如何防止 Matplotlib 地图中注释中的标签重叠?
我正在尝试防止下面美国东北部地图中的标签重叠。我试图为该地区的某些州打开和关闭标签,但是肯定有一种更好的方法。以下是我的代码和输出。
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)
I am trying to prevent the labels in the Northeast US map below from overlapping. I have tried to turn labels on and off for certain states in the region, but there definitely is a better way of doing it. Below is my code and output.
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
显然,如果没有您的数据,我无法对其进行测试,但如果您愿意使用
adjustText
再次尝试,您可以尝试将您的label.apply(...)
替换为类似的内容:我不知道
adjust_text
如何处理注释,所以如果这不起作用,您可以尝试将其转换为plt.text
。(matplotlib 类
注释
继承自Text
类)Obviously I cannot test it without your data but if you're willing to try again with
adjustText
you could try replacing yourlabel.apply(...)
with something like that:I don't know how
adjust_text
deals with annotations, so if this doesn't work, you could try converting it toplt.text
.(The matplotlib class
Annotation
inherits from theText
class)