I am plotting quarterly data spanning 20 years. Running the code below, the plot displays x-tick labels as every fifth year. I would like to display every year. Similar posts on SO suggest using matplotlib.dates, but I can't seem to make this work for my use case. How can I display each year on the x-axis?
import pandas as pd
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
# read home sales data
df = pd.read_csv('home_sales.csv',
parse_dates=['deed_date'])
# create column with year-quarter of sale
df['sale_quarter'] = df['deed_date'].dt.to_period("Q")
# group by year-quarter and find average price
grouped = res_sales.groupby('sale_quarter')['sale_price'].mean() / 1000
# convert to dataframe
grouped = pd.DataFrame(grouped)
# name column
grouped.columns = ['average']
#plot
ax = grouped.plot()
# adding the code below removes all tick labels
ax.xaxis.set_major_locator(mdates.YearLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))