Matplotlib图表注释位置异常:如何将注释移至箭头后端?
问题描述
我选取了部分国家子集,用于对比人均GDP(gdp_ppp)与地理纬度(lat),编写了如下Matplotlib代码:
country_sub.plot(kind='scatter', figsize=(6, 4), grid=True, x=lat_col, y=gdp_ppp_col) gdp_ppp_col = "gdp_ppp" lat_col = "lat" position_text = { "Israel": (31.04605, 57_758), "United States": (37.09024, 75_269), "Spain": (40.463667, 29_385), "Bulgaria": (42.733883, 13_129), "Germany": (51.165691, 48_845), "Ireland": (53.41291, 105_362), "Iceland": (64.963051, 74_663) } for country, pos_text in position_text.items(): pos_data_x = country_sub[lat_col].loc[country] pos_data_y = country_sub[gdp_ppp_col].loc[country] country = "U.S." if country == "United States" else country plt.annotate(country, xy=(pos_data_x, pos_data_y), xytext=pos_text, fontsize=12, arrowprops=dict(facecolor='black', arrowstyle='->') ) plt.plot(pos_data_x, pos_data_y, "ro") plt.axis([25, 70, -5000, 125000]) plt.show()
但生成的图表中注释位置距离不当,请问能否将国家注释移至箭头的后端?
解决方案
当然可以,只需调整plt.annotate()的文本对齐参数,让注释紧贴箭头末端(即你设置的xytext位置),具体修改如下:
- 在
plt.annotate()中添加ha='center'(水平居中)和va='center'(垂直居中),确保文本与箭头末端精准对齐; - 可选:通过
arrowprops的shrink参数微调箭头与数据点、文本的间距,避免元素重叠。
修改后的核心代码片段:
plt.annotate(country, xy=(pos_data_x, pos_data_y), xytext=pos_text, fontsize=12, ha='center', va='center', # 让文本对齐到箭头末端 arrowprops=dict(facecolor='black', arrowstyle='->', shrink=0.05) # 可选:缩小箭头两端间距 )
另外注意代码里的一个小问题:变量定义顺序错误,gdp_ppp_col和lat_col在绘图之后才定义,首次运行会报错,需将这两行移到绘图代码之前:
gdp_ppp_col = "gdp_ppp" lat_col = "lat" country_sub.plot(kind='scatter', figsize=(6, 4), grid=True, x=lat_col, y=gdp_ppp_col)
内容的提问来源于stack exchange,提问作者Englishman Bob
相关产品推荐
相关产品推荐

