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

为1秒采样数据散点图X轴设置分钟次刻度报OverflowError如何解决

问题原因

pandas 绘制时间序列图表时,默认会将 X 轴的时间转为纳秒级整数时间戳,和 matplotlib 日期定位器(比如MinuteLocator)要求的浮点型日期单位不兼容,数值量级差距过大就会触发OverflowError: int too big to convert报错。

解决方案

最简单的方案是在调用df.plot()时添加x_compat=True参数,启用 pandas 对 matplotlib 日期格式的兼容模式,修改后即可正常设置分钟级次刻度。

完整可运行代码

import matplotlib.pyplot as plt
from matplotlib.dates import MinuteLocator
import pandas as pd
import numpy as np

# 生成测试数据集
ndex = pd.date_range('2021-08-01 07:07:07', '2021-08-01 07:41:12', freq='1S', name='Time') 
df = pd.DataFrame(data=np.random.randint(1, 100, len(ndex)), index=ndex, columns=['A'])

fig, ax = plt.subplots()
# 添加x_compat=True启用matplotlib日期兼容
df.plot(color='red', marker='x', lw=0, ms=0.2, ax=ax, x_compat=True)

# 分钟级次刻度设置可正常执行
ax.xaxis.set_minor_locator(MinuteLocator())
plt.show()

可选替代方案

你也可以直接使用 matplotlib 原生的plot方法绘制,默认就支持日期定位器:

fig, ax = plt.subplots()
ax.plot(df.index, df['A'], color='red', marker='x', lw=0, ms=0.2)
ax.xaxis.set_minor_locator(MinuteLocator())
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:15:04