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

如何在Matplotlib中移除Python可变频率数据的周末间隔?

移除可变频率时间序列图表中的周末间隙

我查找过相关解决方案,但均无法完全满足需求。假设我们有如下pandas可变频率时间序列数据:

import pandas as pd
testDf = pd.DataFrame(
    {'ImpliedVolatility': {
        pd.Timestamp('2022-11-30 16:20:00+0100'): 19.1269013106775,
        pd.Timestamp('2022-11-30 16:30:00+0100'): 19.0800712368193,
        pd.Timestamp('2022-12-01 15:20:00+0100'): 19.5300982613676,
        pd.Timestamp('2022-12-02 09:00:00+0100'): 18.8579952967423,
        pd.Timestamp('2022-12-02 09:20:00+0100'): 18.6791915364582,
        pd.Timestamp('2022-12-02 15:10:00+0100'): 18.5538057657658,
        pd.Timestamp('2022-12-02 15:20:00+0100'): 18.6965706501837,
        pd.Timestamp('2022-12-02 15:50:00+0100'): 17.5678872272944,
        pd.Timestamp('2022-12-05 09:00:00+0100'): 18.2304285690717}})

用常规方式可以轻松绘制出图表:

import matplotlib.pyplot as plt
fig1, ax1 = plt.subplots()
fig1.autofmt_xdate()
ax1.plot(testDf.ImpliedVolatility, 'o-')
plt.show()

含周末间隙的图表

但我希望移除图表中的周末间隙,具体来说是移除周五午夜至周日午夜的间隔。

网上的解决方案存在诸多问题,最常见的是会将刻度频率重置为固定间隔,示例代码如下:

import numpy as np
import matplotlib.ticker as ticker
fig, axes = plt.subplots(ncols=1)

# 自定义格式化器
N = len(testDf)
ind = np.arange(N)  # 均匀分布的绘图索引

def format_date(x, pos=None):
    thisind = np.clip(int(x + 0.5), 0, N - 1)
    return testDf.index[thisind].strftime('%Y-%m-%d %Hh')

ax = axes
ax.plot(ind, testDf.ImpliedVolatility, 'o-')
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
fig.autofmt_xdate()

plt.show()

含固定间隔的工作日图表

这种方案并不适用于可变频率数据。

注:理想情况是移除所有非交易时间,但不同交易所规则不同,本文关注EUREX期权交易所的数据。

我尝试过包括StackOverflow在内的多种在线方案,它们普遍存在重置X轴刻度频率为固定间隔的问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 22:56:29