pandas DatetimeIndex to matplotlib x-ticks

Viewed 288

I have a pandas Dateframe with a date index looking like this:

Date
2020-09-03
2020-09-04
2020-09-07 
2020-09-08

The dates are missing a few entries, since its only data for weekdays.

The thing I want to do is: Plot the figure and set an x tick on every Monday of the week.

So far I've tried:

date_form = DateFormatter("%d. %b %Y")
ax4.xaxis.set_major_formatter(date_form)
ax4.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=MO))

But it will start with 1970 and not with the actual date index.

Then I tried to:

mdates.set_epoch('First day of my data')

But this won't help since Saturday and Sunday is skipped in my original Index.

Any ideas what I could do?

1 Answers

If you draw a line plot with one axis of datetime type, the most natural solution is to use plot_date.

I created an example DataFrame like below:

            Amount
Date              
2020-08-24     210
2020-08-25     220
2020-08-26     240
2020-08-27     215
2020-08-28     243
...

Date (the index) is of datetime type.

The code to draw is:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

fig, ax = plt.subplots()
plt.xticks(rotation=30)
ax.plot_date(df.index, df.Amount, linestyle='solid')
ax.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=0))
plt.grid()
plt.show()

The picture I got is:

enter image description here

As you can see, there is absolutely no problem with x ticks and they are just on Mondays, as you want.

Related