Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: quarterly minor tick labels

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)
like image 927
measure_theory Avatar asked Mar 04 '23 12:03

measure_theory


1 Answers

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))
like image 134
ImportanceOfBeingErnest Avatar answered Mar 09 '23 00:03

ImportanceOfBeingErnest