python matplotlib - How to make sure x axis values to be the same of the source data

Viewed 86

I am trying to do some plotting on matplotlib. Here's my data df:

     datadate       loss_CF
0  2020-03-31  14744.417859
1  2020-06-30  18443.540626
2  2020-09-30  21902.934212
3  2020-12-31  24743.491101
4  2021-03-31  22532.267947
5  2021-06-30  21835.597756
6  2021-09-30  21607.682299
7  2021-12-31  22898.842686
8  2022-03-31  21513.368257
9  2022-06-30  20412.728656
10 2022-09-30  19598.518147
11 2022-12-31  18220.543880

Here's my code to plot it:

import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

#date = df['datadate'].dt.strftime('%y-%b')
fig, ax = plt.subplots()
y_formatter = ticker.StrMethodFormatter('${x:,.0f}')
x_formatter = DateFormatter('%b-%y')
ax.yaxis.set_major_formatter(y_formatter)
ax.xaxis.set_major_formatter(x_formatter)
plt.plot(df['datadate'], df['loss_CF'])
plt.show()

Here's the figure I got:

enter image description here

Is there a way to change the x axis values to be the datadate in df? In other words, I would like them to all be quarter-end month instead of Jan, May, etc. For example, the first tick corresponding to the first data point should be Mar-20. How can I do that? I figure ax.set_xticks and ax.set_xticklabels might be the answer but after trying them a long time I still can't get the ideal plot I want.

1 Answers

Since your data is not too long, you can just plot against the strings:

fig, ax = plt.subplots(figsize=(10,6))

plt.plot(df['datadate'].dt.strftime('%b-%y'), df['loss_CF'])
plt.show()

Output:

enter image description here

Also, you can try pandas' plot function:

fig, ax = plt.subplots(figsize=(10,6))
x_formatter = DateFormatter('%b-%y')
(df.assign(date=df.datadate.dt.to_period('Q'))
   .plot(x='date',y='loss_CF',ax=ax)
)

Output:

enter image description here

Related