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

Matplotlib:如何将第二个图表与第一个图表的指定日期对齐

需求实现:将次级向量数据与主图表指定日期对齐绘制

问题说明

现有含2列的DataFrame,需以date列为X轴、第一列数据为Y轴绘制折线图。另有次级数据字典,key为存在于主数据集的日期,value是一个向量,其中向量的索引20位置对应该key日期。需要将该次级向量与主图表的指定日期对齐绘制,优先实现同一图表内的对齐效果。


方案1:同一图表双轴对齐

在同一画布内通过双轴实现蓝色向量与目标日期的精准对齐,直观展示两组数据的关联关系。

import pandas as pd, numpy as np
import matplotlib.pyplot as plt

np.random.seed(0)

# 主数据
df = pd.DataFrame({'date': pd.date_range('2020-11-30', periods=31), 'temp': np.arange(1, 32)})
# 次级数据:key为日期,向量索引20对应该日期
ml = {'2020-12-15': list(np.random.rand(56))}

# 定位目标日期及对应X轴位置
target_date = pd.to_datetime('2020-12-15')
target_pos = df[df['date'] == target_date].index[0]
# 计算次级向量的X轴坐标:确保索引20刚好对应目标日期位置
vec_x = np.arange(target_pos - 20, target_pos - 20 + len(ml[target_date.strftime('%Y-%m-%d')]))

fig, ax1 = plt.subplots(dpi=120)

# 绘制主温度曲线
ax1.plot(df.index, df['temp'], '-o', c='orange', label='温度(T)')
ax1.set_xlabel('日期')
ax1.set_ylabel('温度')
ax1.set_xticks(df.index)
ax1.set_xticklabels(df['date'].dt.strftime('%Y-%m-%d'), rotation=90)
ax1.legend(loc='upper left')

# 创建双轴绘制次级向量
ax2 = ax1.twinx()
ax2.plot(vec_x, ml[target_date.strftime('%Y-%m-%d')], '-o', c='blue', label='ML数据(2020-12-15)')
ax2.set_ylabel('ML向量值')
ax2.legend(loc='upper right')

# 添加对齐参考线
ax1.axvline(x=target_pos, color='gray', linestyle='--', alpha=0.7, label='对齐日期')
ax1.legend()

plt.tight_layout()
plt.show()

方案2:子图共享X轴对齐

通过共享X轴的子图布局,让次级向量的索引20位置与主图目标日期垂直对齐,适合需要分开展示两组数据的场景。

import pandas as pd, numpy as np
import matplotlib.pyplot as plt

np.random.seed(0)

df = pd.DataFrame({'date': pd.date_range('2020-11-30', periods=31), 'temp': np.arange(1, 32)})
ml = {'2020-12-15': list(np.random.rand(56))}

# 定位目标日期及对应X轴位置
target_date = pd.to_datetime('2020-12-15')
target_pos = df[df['date'] == target_date].index[0]
# 计算次级向量的X轴坐标
vec_x = np.arange(target_pos - 20, target_pos - 20 + len(ml[target_date.strftime('%Y-%m-%d')]))

# 创建共享X轴的子图
fig, (ax1, ax2) = plt.subplots(2, 1, dpi=120, sharex=True)

# 绘制主温度曲线
ax1.plot(df.index, df['temp'], '-o', c='orange', label='温度(T)')
ax1.set_ylabel('温度')
ax1.legend(loc='upper left')
ax1.axvline(x=target_pos, color='gray', linestyle='--', alpha=0.7)

# 绘制次级向量曲线
ax2.plot(vec_x, ml[target_date.strftime('%Y-%m-%d')], '-o', c='blue', label='ML数据(2020-12-15)')
ax2.set_xlabel('日期')
ax2.set_ylabel('ML向量值')
ax2.set_xticks(df.index)
ax2.set_xticklabels(df['date'].dt.strftime('%Y-%m-%d'), rotation=90)
ax2.legend(loc='upper left')
ax2.axvline(x=target_pos, color='gray', linestyle='--', alpha=0.7)

plt.tight_layout()
plt.show()

关键逻辑说明

  • 先定位目标日期在主DataFrame索引中的位置target_pos
  • 根据次级向量的长度和“索引20对应目标日期”的规则,计算向量对应的X轴坐标vec_x,确保向量索引20刚好落在target_pos上
  • 通过双轴或共享X轴的方式,保证两组数据的X轴刻度对齐,实现蓝色线条与指定日期的精准对应

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 15:55:20