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

如何在Matplotlib中匹配指定年份的x轴位置添加网格线

实现匹配new_year列的x轴网格线添加

核心方法

提取new_year列中的目标年份,利用Matplotlib的vlines()方法在对应x轴位置添加垂直网格线,结合Seaborn绘图后的Axes对象即可完成需求。

完整代码示例

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# 假设已完成数据筛选,filtered_df是处理后的数据集
filtered_df = pd.read_excel('your_processed_data.xlsx')

# 创建绘图对象并绘制散点图+折线图
fig, ax = plt.subplots(figsize=(10, 6))
sns.scatterplot(data=filtered_df, x='year', y='your_value_column', ax=ax, label='散点数据')
sns.lineplot(data=filtered_df, x='year', y='your_value_column', ax=ax, label='折线趋势')

# 提取new_year中的唯一年份(避免重复绘制),确保与year列类型一致
target_years = filtered_df['new_year'].drop_duplicates().astype(int).tolist()
# 若year是datetime类型,需同步转换:
# filtered_df['new_year'] = pd.to_datetime(filtered_df['new_year'])
# target_years = filtered_df['new_year'].drop_duplicates().tolist()

# 添加垂直网格线
ax.vlines(
    x=target_years,
    ymin=ax.get_ylim()[0],
    ymax=ax.get_ylim()[1],
    colors='#ff4444',  # 自定义颜色
    linestyles='--',   # 虚线样式
    alpha=0.6,         # 透明度
    label='目标年份网格线'
)

# 调整图表细节
ax.set_xlabel('年份')
ax.set_ylabel('指标值')
ax.legend()
plt.show()

关键注意事项

  • 类型匹配:必须保证new_year的年份类型与x轴year列完全一致(比如都是整数年份或datetime格式),否则网格线会出现位置偏移。
  • 样式区分:通过调整颜色、线型和透明度,让目标网格线和默认网格线形成视觉区分,突出重点年份。
  • 批量效率:使用vlines()可以一次性添加多个年份的网格线,比循环调用ax.axvline()更简洁高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 00:50:34