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

如何为2D直方图X轴设置日期并避免Matplotlib轴格式化溢出错误?

解决2D直方图X轴日期格式化的溢出错误

问题背景

我有一组跨度20余年的月平均时间序列数据,已存入pandas DataFrame,索引为datetime对象。绘制时间与质子速度的2D直方图子图后,X轴显示为默认的非日期格式;尝试用matplotlib的日期定位器/格式化器调整X轴时,频繁触发OverflowError: int too big to convert错误。

已用导入代码

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime, date, time
import matplotlib.dates as mdates

DataFrame示例

Datetime      proton_density  proton_temp  He4toprotons  proton_speed  x_dot_RTN  Proton Mass Flux
----------------------------------------------------------------------------------------                     
1998-01-23    11.625          58930.0      0.0224        380.90        379.91     7.406307e-19
1998-02-19    9.569           64302.0      0.0294        380.99        380.23     6.097867e-19
1998-03-18    8.767           66770.0      0.0348        384.00        383.19     5.630929e-19
...
2022-01-05    7.280           85944.0      0.0310        434.17        433.01     5.286752e-19

原绘图代码(触发错误的版本)

ax_example = plt.subplot2grid((3, 6), (2, 1), colspan = 2)

H,xedges,yedges = np.histogram2d(SWEPAM_dataframe.index, SWEPAM_dataframe.proton_speed, bins=[50,50])
ax_example.pcolor(xedges, yedges, H.T)
ax_example.set_xlabel("Year")
ax_example.set_ylabel("Proton Speed (km/s)")

解决方案

问题根源

np.histogram2d处理datetime索引时,会自动将其转换为纳秒级整数时间戳,数值过大超出matplotlib日期工具的处理范围,从而引发溢出错误。

修正后的完整代码

ax_example = plt.subplot2grid((3, 6), (2, 1), colspan = 2)

# 将datetime索引转换为matplotlib兼容的浮点数日期格式
x_vals = mdates.date2num(SWEPAM_dataframe.index)

# 用转换后的数值计算2D直方图
H, xedges, yedges = np.histogram2d(x_vals, SWEPAM_dataframe.proton_speed, bins=[50,50])
ax_example.pcolor(xedges, yedges, H.T)

# 设置X轴日期格式
ax_example.xaxis.set_major_locator(mdates.YearLocator(5))  # 每5年显示一个刻度
ax_example.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))  # 格式化为年份
plt.setp(ax_example.get_xticklabels(), rotation=45, ha='right')  # 旋转标签避免重叠

ax_example.set_xlabel("Year")
ax_example.set_ylabel("Proton Speed (km/s)")

plt.tight_layout()
plt.show()

关键说明

  1. mdates.date2num():将datetime对象转换为matplotlib内部使用的浮点数(以1970-01-01为基准的天数),避免大整数溢出。
  2. 日期定位器/格式化器:使用YearLocator控制刻度间隔,DateFormatter指定显示格式,同时旋转标签提升可读性。
  3. plt.tight_layout():自动调整子图间距,防止标签被截断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 21:34:58