You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib注释箭头缺失箭身:如何生成带箭身的注释箭头?

修复Matplotlib注释箭头缺失箭身的问题

问题核心

箭头没有箭身是因为arrowprops未指定箭身宽度参数,同时代码存在变量定义顺序错误、坐标轴范围变量缺失的问题,导致图表生成异常。

修复步骤

  1. 调整变量定义顺序:把gdp_ppp_col和lat_col的定义移到绘图语句之前,避免未定义报错。
  2. 补充坐标轴范围:添加min_lat和max_lat的定义,匹配数据的纬度区间。
  3. 修正箭头参数:添加linewidth设置箭身粗细,用color统一箭头头部与箭身的颜色,优化参数让箭头效果符合需求。

修正后的完整代码

import matplotlib.pyplot as plt

# 全局字体配置
plt.rc('font', size=12)
plt.rc('axes', labelsize=14, titlesize=14)
plt.rc('legend', fontsize=12)
plt.rc('xtick', labelsize=10)
plt.rc('ytick', labelsize=10)

# 先定义列名变量,再执行绘图
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)

# 设置坐标轴范围
min_gdp_ppp = 25
max_gdp_ppp = 125_000
min_lat = 25  # 根据实际数据调整合适值
max_lat = 70   # 根据实际数据调整合适值

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_label = "U.S." if country == "United States" else country
    plt.annotate(country_label, 
                 xy=(pos_data_x, pos_data_y),
                 xytext=pos_text, 
                 fontsize=12,
                 # 修复箭头核心参数
                 arrowprops=dict(color='black', 
                                linewidth=1.5,  # 箭身粗细
                                width=1.5,      # 箭头头部纵向宽度
                                headwidth=5,    # 箭头头部横向宽度
                                shrink=0.08))
    plt.plot(pos_data_x, pos_data_y, "ro")

plt.axis([min_lat, max_lat, min_gdp_ppp, max_gdp_ppp])
plt.show()

关键参数解释

  • linewidth:控制箭身粗细,这是之前缺失的核心参数。
  • color:统一设置箭头头部和箭身的颜色,若需区分,可单独用facecolor设置头部填充色,edgecolor设置箭身与头部边框色。
  • width:仅控制箭头头部的纵向宽度,与箭身无关。
  • shrink:让箭头两端与数据点、标注文本保持小距离,避免重叠。

内容的提问来源于stack exchange,提问作者Englishman Bob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 15:24:51