Display end of month instead of first day of month

1.1k Views Asked by At

When I plot the dataframe using matplotlib, it displays the first day of the month. Instead, what i really want is to display the end of the month. How can i do that using matplotlib ?

Date                  Miles  
2020-01-31            410.364502
2020-02-29           1190.701827
2020-03-31           2400.855076
2020-04-30            526.747960
2020-05-31           2044.158990
2020-06-30          13983.470617
2020-07-31          18911.396787
2020-08-31           9219.378732
2020-09-30          16039.311330
2020-10-31          16847.898328
2020-11-30           7452.507720


fig, ax = plt.subplots(dpi=800)
ax.plot(general_trend.index, general_trend['Miles'], linewidth=0.8,color='red')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax.legend(loc='upper right', ncol=2,fontsize=4.5)
ax.tick_params(axis='both', which='major', labelsize=6)
fig.autofmt_xdate()
plt.show()

enter image description here

1

There are 1 best solutions below

0
On BEST ANSWER

There may be many other ways to do it, but you can use a locator and a formatter to specify the end of the month with a display basis of bymonthday=-1 for the month.

general_trend['Date'] = pd.to_datetime(general_trend['Date'])
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

fig, ax = plt.subplots(figsize=(4,3),dpi=200)
ax.plot(general_trend['Date'], general_trend['Miles'], linewidth=0.8, color='red', label='Miles')

months = mdates.MonthLocator(interval=1, bymonthday=-1)
months_fmt = mdates.DateFormatter('%Y-%m-%d')
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(months_fmt)

ax.legend(loc='upper right', ncol=2, fontsize=4.5)
ax.tick_params(axis='x', which='major', labelsize=6, labelrotation=45)

plt.show()

enter image description here