pythonpandasdatetimematplotlib

Uneven intervals between x-axis with datetime


I am currently experiencing an issue where the spaces between ticks on my plot appear to have uneven intervals when using a DatetimeIndex for my x-axis. The code is as follows:

x = pd.date_range('2018-11-03', '2018-12-30')
plt.plot(x, np.arange(len(x)))
plt.xticks(rotation=45)

enter image description here

Note the two instances in which the dates do not increment by the typical 7-day period. Even after extending the time period, the issue persists:

x = pd.date_range('2018-11-03', '2019-03-20')
plt.plot(x, np.arange(len(x)))
plt.xticks(rotation=45)

enter image description here

How can I override this behavior to have standard 7-day intervals on my plot? Thank you.


Solution

  • You can use matplotlib's ticker module to customize tick locations:

    import matplotlib.pyplot as plt
    import pandas as pd
    import matplotlib.ticker as ticker
    
    x = pd.date_range('2018-11-03', '2019-03-20')
    plt.plot(x, np.arange(len(x)))
    plt.xticks(rotation=45)
    ax=plt.gca()
    ax.xaxis.set_major_locator(ticker.MultipleLocator(7))
    

    The above script returns the following image:

    enter image description here