I have quarterly data that I'm trying to plot using Matplotlib. I want the major xtick labels to show the years and the minor xtick labels show the quarters.
All I can find, however, is for monthly data. That is, the following code (using matplotlib's mdates function) will make the minor xticks monthly, but I don't see a quarterly option...
Any help?
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
A = pd.DataFrame(np.random.rand(6*4))
A.index = pd.date_range(start = "2017", periods = len(A), freq = "QS")
fig, ax = plt.subplots(figsize = (10,6))
ax.plot(A)
years = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
yearsFmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
MonthLocator
takes several arguments. You can use bymonth
(the first one) and specify the months for which you want to have ticks. A quarter comprises 3 months, so 1,4,7,10
should be what you're after.
months = mdates.MonthLocator((1,4,7,10))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With