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

如何用两个DataFrame和循环绘制按ticker分组的叠加子图

按标的叠加绘制样本内真实值与预测值子图

问题背景

我拥有两个DataFrame:

df1:
date, ticker, y_true
1/1, A, 10
1/2, A, 8
...
1/1, B, 10
1/2, B, 8
...

df2:
date, ticker, y_predict, y_predict_upper, y_predict_lower
8/1, A, 10,13,8
8/2, A, 8,9,1
...
8/1, B, 10,13,8
8/2, B, 8,9,1
...

需要按ticker为每个标的绘制子图,每个子图中叠加df1的真实值和df2的预测值(含上下置信区间),且df2的日期属于df1的样本内日期。已实现df1的绘图代码,需完成叠加部分。

解决方案

核心修改要点

  • 统一两个DataFrame的日期格式为datetime类型,避免绘图时日期错位
  • 在循环中对每个标的,先绘制真实值,再叠加预测线和置信区间填充
  • 优化图表样式,提升可读性

修改后的完整代码

import pandas as pd
import matplotlib.pyplot as plt

# 转换date列为datetime类型(确保日期轴对齐)
df1['date'] = pd.to_datetime(df1['date'])
df2['date'] = pd.to_datetime(df2['date'])

ticker_list = ['A','B','C',...]
# 定义子图网格
fig, axs = plt.subplots(nrows=8, ncols=1, figsize=(15, 60), dpi=150)

# 遍历标的和对应子图轴
for ticker, ax in zip(ticker_list, axs.ravel()):
    # 绘制当前标的的真实值
    df1_ticker = df1[df1["ticker"] == ticker]
    df1_ticker.plot(x='date', y='y_true', ax=ax, label='真实值', color='blue', linewidth=2)
    
    # 绘制当前标的的预测值
    df2_ticker = df2[df2["ticker"] == ticker]
    df2_ticker.plot(x='date', y='y_predict', ax=ax, label='预测值', color='red', linestyle='--', linewidth=2)
    
    # 绘制预测值的置信区间填充
    ax.fill_between(df2_ticker['date'], 
                    df2_ticker['y_predict_lower'], 
                    df2_ticker['y_predict_upper'], 
                    color='orange', alpha=0.2, label='置信区间')
    
    # 图表格式化
    ax.set_title(f'{ticker.upper()} 真实值与样本内预测值对比', fontsize=14)
    ax.legend(loc='upper right', fontsize=12)
    ax.set_xlabel('日期', fontsize=12)
    ax.set_ylabel('数值', fontsize=12)

# 调整子图间距,避免标题、标签重叠
plt.tight_layout()
plt.show()

关键细节说明

  • 日期统一:必须将date列转为datetime类型,否则两个DataFrame的日期可能因格式不一致导致绘图错位
  • 叠加逻辑:所有绘图操作都针对同一个ax对象执行,就能实现同子图内的图层叠加
  • 置信区间:使用fill_between()函数生成上下区间的阴影填充,直观展示预测的波动范围
  • 样式优化:通过区分线条颜色、样式,添加清晰的图例,让每个子图的信息更易解读

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 05:09:11