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

日期索引DataFrame绘图出现跨非营业时段长直线如何解决

分时交易数据绘制去除跨交易日长连线方案

问题原因

pandas绘制时间序列时会将datetime索引识别为连续数值型轴,即使剔除非营业时段数据,前后交易日的时间间隔仍会体现在x轴上,导致两个交易日首尾数据出现长连线。
原错误绘图效果

方案1:等距索引绘制(最常用,走势展示友好)

将数据按顺序映射为等距的整数索引,再手动替换x轴刻度为时间标签,彻底消除非交易时间的间隔影响:

import pandas as pd
import matplotlib.pyplot as plt

# 重置索引将时间列转为普通列
df_draw = df.reset_index()
# 用整数索引作为x轴绘制,保证每个数据点间隔相等
ax = df_draw.plot(y=df.columns, use_index=True, figsize=(12,6))
# 按需调整x轴刻度显示密度,避免标签重叠,示例每4个点显示一次刻度
xticks_pos = ax.get_xticks()
ax.set_xticks(xticks_pos[::4])
ax.set_xticklabels(
    [df_draw['date'].iloc[int(i)].strftime('%m-%d %H:%M') for i in xticks_pos[::4]],
    rotation=30
)
plt.tight_layout()
plt.show()

方案2:按交易日分组绘制(保留真实时间轴)

如果需要保留x轴的真实时间分布,可按交易日拆分数据分别绘制,不同交易日的曲线不会自动连接:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(12,6))
# 按日期分组,每个交易日单独绘制
for trade_date, group_data in df.groupby(df.index.date):
    group_data.plot(ax=ax, legend=False)
# 去重处理图例
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[:len(df.columns)], labels[:len(df.columns)])
plt.xticks(rotation=30)
plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 23:45:01