Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib - 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.

like image 276
GardenQuant Avatar asked Jan 27 '23 22:01

GardenQuant


1 Answers

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

like image 113
Sheldon Avatar answered Jan 31 '23 07:01

Sheldon