0

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'))  

eric s
  • 197
  • 1
  • 6
  • `ax = grouped.plot(x_compat=True)` as explained here: [pandas .plot() x-axis tick frequency -- how can I show more ticks?](https://stackoverflow.com/questions/39714724/pandas-plot-x-axis-tick-frequency-how-can-i-show-more-ticks) The relevant section in the pandas docs is [here](https://pandas.pydata.org/pandas-docs/stable/user_guide/visualization.html#suppressing-tick-resolution-adjustment). – Mr. T Feb 15 '22 at 08:07
  • Thanks @Mr.T, but this didn't fix the issue; it just changed the formatting of the tick labels, but not the frequency. I wonder if there using quarters introduces the difficulty. – eric s Mar 01 '22 at 21:47
  • Well, then I suggest providing an MCVE including a sample input, current output, and expected output. I tried it with random data, and `ax = grouped.plot(x_compat=True)` solved your problem. – Mr. T Mar 03 '22 at 09:56

0 Answers0