0

I'm trying to make a time series plot, using Pandas and matplotlib, with ticked weekdays (Monday) on x axis. However, I've encountered a strange behavior which I believe is caused by (wrong?) handling of datetime indexing in pandas.Series.plot function.

From the documentation for pandas.Series.plot (also in pandas.DataFrame.plot):

  • use_index bool, default True. Use index as ticks for x axis.

However, although the index is of DatetimeIndex type, it looks like it is not considered as such (probably handled as string?).

Consider the following code which tries to create the same plot using three different approaches:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl


idx = pd.date_range(start='2020-10-02', periods=35)
Y = np.cumsum(np.random.uniform(0, 10, idx.size))

ts = pd.Series(Y, idx)

fig, axes = plt.subplots(figsize=(10, 6), nrows=3, constrained_layout=True)

ts.plot(kind='bar', ax=axes[0]) # use_index=True is used by defualt
axes[0].xaxis.set_major_locator(mpl.dates.WeekdayLocator(interval=1, byweekday=mpl.dates.MONDAY))

ts.plot(kind='bar', ax=axes[1])
axes[1].xaxis.set_major_locator(mpl.dates.WeekdayLocator(interval=1, byweekday=mpl.dates.MONDAY))
axes[1].xaxis.set_major_formatter(mpl.dates.DateFormatter('%Y-%m-%d'))

axes[2].bar(ts.index, ts.values)
axes[2].xaxis.set_major_locator(mpl.dates.WeekdayLocator(interval=1, byweekday=mpl.dates.MONDAY))
axes[2].xaxis.set_major_formatter(mpl.dates.DateFormatter('%Y-%m-%d'))

The results is enter image description here

I expected all three plots would be more-or-less the same. And they are, excluding the ticks of x axis (which should mark Monday's dates). As i see it, the DatetimeIndex is not really recognized correctly in pandas.Series.plot. The dates on the first plot are correct, but the ticked dates are not Mondays. What is even more annoying, if a new format is applied on the ticks (second plot) even the dates are wrong!

The behavior of bar(ts.index, ts.values) is correct and marks Mondays as expected.

sivic
  • 533
  • 6
  • 12
  • 1
    This [answer](https://stackoverflow.com/a/30135182/9245853) discusses the issue you are seeing in the second subplot. – BigBen Nov 05 '20 at 14:53
  • Can you post versions of the packages? I do not get the same plot from your code – Tom Nov 05 '20 at 15:24
  • Hi @Tom, I've now tried the code on my home PC and it does look different than the one above: It doesn't have any ticks whatsoever in first two subplots! Also very strange... The versions are:`pd.__version__ '0.25.3' mpl.__version__ '3.0.2'`. Initial problem occurred on relatively new Anaconda installation (approx. a month ago), I'll check the versions tomorrow. – sivic Nov 05 '20 at 20:40
  • @Tom the versions for which original issue is encountered: `pd.__version__ '1.1.3' mpl.__version__ '3.3.1'` – sivic Nov 06 '20 at 18:41

0 Answers0