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

matplotlib折线图标注过密 如何设置仅显示偶数周的数据标签

解决方法

你只需要在标注的遍历逻辑中增加周数奇偶性判断,仅当周数为偶数时执行标注操作即可,具体修改如下:

核心修改点

原标注逻辑没有做过滤,所有周数都会生成标注,现在新增周数 % 2 == 0的判断条件即可:

# 2019年数据标注修改后
for i,j in zip(CA_plot_df.W, CA_plot_df[2019]):
    # 仅偶数周生成标注
    if i % 2 == 0:
        ax.annotate('%s' % round(j), xy=(i,j), xytext=(-2,5), textcoords='offset points')

2021年的标注循环做同样修改:

# 2021年数据标注修改后
for i,j in zip(df_2021.W, df_2021[2021]):
    if i % 2 == 0:
        ax.annotate('%s' % round(j), xy=(i,j), xytext=(-2,5), textcoords='offset points')

补充说明

  • 如果你的数据中W字段为字符串格式,需要先转成整数再做判断:if int(i) % 2 == 0
  • 后续如果需要调整标注密度,比如每3周、每4周标注一次,只需要把判断条件里的2改成对应数值即可,比如每3周标注就改为i % 3 == 0
  • 目前你的代码中2020年数据没有加标注,如果后续需要添加,也可以复用同样的判断逻辑

完整修改后代码

import pandas as pd
import matplotlib.pyplot as plt

CA_plot_df = CA_Data.pivot_table('ED Arrivals', ['W'], 'Year').reset_index()
CA_plot_df = CA_plot_df[1:-1]
df_2021 = CA_plot_df[['W',2021]].dropna()[:-1]

plt.style.use('ggplot')
plt.rcParams['axes.facecolor'] = 'white'

fig = plt.figure(figsize = (15,8))
ax = fig.add_subplot(111)

plt.plot(CA_plot_df.W, CA_plot_df[2019], label = 'year 2019', color = '#407c38', linewidth = 2)

# 修改后的2019年标注逻辑
for i,j in zip(CA_plot_df.W,CA_plot_df[2019]):
    if i % 2 == 0:
        ax.annotate('%s' %round(j), xy=(i,j), xytext=(-2,5), textcoords='offset points')

plt.plot(CA_plot_df.W, CA_plot_df[2020], label = 'year 2020', color = '#b3b3b3', linewidth = 2)
plt.plot(df_2021.W, df_2021[2021], label = 'year 2021',color = '#d64550', linewidth = 2)

# 修改后的2021年标注逻辑
for i,j in zip(df_2021.W,df_2021[2021]):
    if i % 2 == 0:
        ax.annotate('%s' %round(j), xy=(i,j), xytext=(-2,5), textcoords='offset points')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 22:15:00