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

Matplotlib折线图为指定年份数据点添加标注的实现方法

Matplotlib折线图指定点位添加文本标注实现方法

核心逻辑:pandas的df.plot()会返回matplotlib的Axes轴对象,拿到这个对象后调用annotate()接口,即可定位到目标年份对应的数据点,添加自定义文本标注,还可以按需调整标注位置、添加指向箭头匹配参考效果。

完整可运行代码

import pandas as pd
import matplotlib.pyplot as plt

# 原有数据集与基础绘图逻辑
data = {
         'Year': ["2000","2001","2002","2003","2004","2005","2006","2007","2008","2009","2010","2011","2012","2013","2014","2015","2016","2017","2018","2019","2020","2021"],
         'Sales':[8.7,5.7,5.8,5.6,5.5,5.3,5,4.8,4.2,4.2,4.1,4.1,4.1,4.1,4.7,4.6,4.8,4.9,5.3,5.4,5.7,5.7],
        }

df = pd.DataFrame(data, columns = ['Year', 'Sales'])
ax = df.plot(x='Year', kind='line', stacked=True,legend=None,xlabel='',ylabel='In percentage (%)')

# 配置需要添加的标注:年份对应标注文本
anno_map = {
    "2000": "GST 10 %, 15 and 20%",
    "2010": "GST 10 %, 18 and 25%",
    "2020": "GST 15 %, 19 and 21%"
}

for year, label_text in anno_map.items():
    # 定位目标点的x索引和y值
    point_x = df[df["Year"] == year].index[0]
    point_y = df.loc[point_x, "Sales"]
    # 添加标注
    ax.annotate(
        label_text,
        xy=(point_x, point_y), # 箭头指向的数据点坐标
        xytext=(point_x, point_y + 0.35), # 文本放置坐标,这里向上偏移0.35避免遮挡折线
        ha="center", # 文本水平居中对齐
        fontsize=8,
        # 配置指向数据点的细箭头,不需要可以删除这行
        arrowprops=dict(arrowstyle="->", color="#666666", linewidth=0.7)
    )

# 调整y轴范围,防止顶部标注被画布截断
ax.set_ylim(bottom=3.8, top=9.5)
plt.tight_layout()
plt.show()

可调参数说明

  • 标注位置:修改xytext的偏移值即可调整文本位置,比如要把标注放在点位右侧,可以改成xytext=(point_x + 0.6, point_y),再把ha参数改成"left"实现左对齐。
  • 箭头样式:不需要箭头直接删除arrowprops参数即可,也可以修改arrowstyle、颜色、线宽参数调整箭头外观。
  • 字体效果:可以通过fontsize、color、weight等参数调整标注文本的大小、颜色、字重。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 02:36:15