BUG: matplotlib invert_xaxis crashes when using datetime · Issue #3990 · pandas-dev/pandas (original) (raw)
From stackoverflow, a question from more than a month ago, but still an issue I think (tested with master).
Basicly, when using ax.invert_xaxis()
with datetime x-values, the following exception is raised:
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)
At first it may not seem an error from pandas, as you can trigger it by using pure matplotlib code, but the error comes from pandas\tseries\converter.py. And more, it is by importing pandas that causes working matplotlib code to work no longer:
import numpy as np import matplotlib.pyplot as plt import datetime
x = np.array([datetime.datetime(2012, 8, 1, 0, 0), datetime.datetime(2012, 9, 1, 0, 0), datetime.datetime(2012, 10, 1, 0, 0)], dtype=object) y = np.array([-1,0,1])
Working matplotlib!
fig, ax = plt.subplots() ax.plot(x,y) ax.invert_xaxis() plt.show()
import pandas as pd
Same matplotlib not working anymore after importing pandas
fig, ax = plt.subplots() ax.plot(x,y) ax.invert_xaxis() plt.show()
CAUSE of the bug:
When using ax.invert_xaxis()
the left and right xlim are interchanged. Because of this the delta
in PandasAutoDateLocator will be negative (https://github.com/pydata/pandas/blob/master/pandas/tseries/converter.py#L241).
This in turn triggers MilliSecondLocator instead of the normal AutoDateLocator, and causes the error as the datetime range is too big for MilliSecondLocator.
What I don't understand is why this is not happening when using pandas plot
to create the axes object (the workaround I gave at stackoverflow):
df = pd.DataFrame(y, index=x, columns=['test'])
This works as expected!
fig, ax = plt.subplots() df.plot(ax=ax) ax.invert_xaxis() plt.show()