0

I have a dataframe as follows. | Date| A | B | |-- | ---- | -- | | Jan-20| 205.0| 232.0 | Feb-20| 328.0 | 338.0

I turn the Date column into a datetime object, set it as the index and graph it.

df['Date'] = pd.to_datetime(df['Date'],format="%b-%y") 
df = df.set_index("Date")
df.plot(kind='line', figsize=(10,5), color=["#FDCE0D","#3A424A"])

However I get the following x-axis where the year is under each instance of January. enter image description here

Is there a way to have the year go next to each month, such as 'Jan 2018'? I know I can perform a .strftime("%b %Y) but I want to keep it as a datetime object as I'm overlaying shading to the graph using datetime ranges.

When I try to format it the following way I get this.

date_fmt = mdates.DateFormatter('%b %Y')
ax.xaxis.set_major_formatter(date_fmt)

enter image description here

fent00
  • 31
  • 1
  • 7

1 Answers1

0

If you assign your plot to a variable (ax), you can do the following.

import matplotlib.dates as mdates

ax.set_xticks(df.index)
date_fmt = mdates.DateFormatter('%b %Y')
ax.xaxis.set_major_formatter(date_fmt)
Sasha Halpern
  • 93
  • 1
  • 10