Skip to main content
 首页 » 编程设计

python之matplotlib "axis.invert_xaxis"在使用日期时间时崩溃

2024年11月01日19zhenyulu

如果我运行以下代码:

import pandas as pd 
from datetime import datetime 
import numpy as np 
import matplotlib.pyplot as plt 
 
#df = pd.DataFrame(np.random.randn(3,1), index=[8,9,10], columns=['test']) 
df = pd.DataFrame(np.random.randn(3,1), index=[datetime(2012,8,1),datetime(2012,9,1),datetime(2012,10,1)], columns=['test']) 
fig = plt.figure() 
ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) 
ax1.invert_xaxis() 
ax1.plot(df.index, df['test']) 
fig.show() 

我得到一个异常(exception):

RuntimeError: MillisecondLocator estimated to generate 5270400 ticks from 2012-08-01 00:00:00+00:00 to 2012-10-01 00:00:00+00:00: exceeds Locator.MAXTICKS* 2 (2000) 

如果我禁用“invert_xaxis”命令,并且索引使用非日期时间值,它也能正常工作。

我在绘制具有无序日期索引的数据框时看到了一些类似的错误报告(例如 here 和 here ),但这在早期版本的 pandas 中已修复。

关于解决方法的任何建议?我正在使用 matplotlib 1.2.1 和 pandas 0.11.0

请您参考如下方法:

作为解决方法:当使用 pandas 的 plot 方法以及之后调用 invert_xaxis 时,它确实对我有用:

fig = plt.figure() 
ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) 
df.plot(ax=ax1) 
ax1.invert_xaxis() 
fig.show() 

更新:自 pandas 0.12(2013 年 7 月)发布以来,此问题现已修复(参见 https://github.com/pydata/pandas/pull/3991 和 https://github.com/pydata/pandas/issues/3990 )。因此不再需要解决方法。