oOHugOo
oOHugOo

Reputation: 13

matplotlib set locator for different subplots

I have several data organized by year. I would like to plot a unique subplot for each different year, and want my locators and formatters to show year and months on the x-axis.

However, I am not able to display different x-axis time range through locators and formatters.

Is there a way to plot this? subplot 1 : 2018-2019 subplot 2 : 2019-2020 subplot 3 : 2020-2021

I tried it this way, I want to use a for loop in case the range of years is huge.

import matplotlib.pyplot as plt
import matplotlib.dates as md
import datetime
years = md.YearLocator()
years_fmt = md.DateFormatter('%Y')
months = md.MonthLocator()
month_fmt = md.DateFormatter('%b')
datax = [datetime.date(2018,10,11), datetime.date(2019,2,10), datetime.date(2020,6,6)]
datay = [1,2,3]
fig, axs = plt.subplots(len(datax), 1)
for idx, ax in enumerate(axs):

    ax.xaxis.set_major_locator(years)
    ax.xaxis.set_major_formatter(years_fmt)
    ax.tick_params(which='major', axis = 'x', pad = 14)
    ax.xaxis.set_minor_locator(months)
    ax.xaxis.set_minor_formatter(month_fmt)
 
    xmin = datetime.date(datax[idx].year,1,1)
    xmax = datetime.date(datax[idx].year+1,1,1)

    ax.set_xlim(left = xmin , right = xmax)       
    ax.set_ylim(0,5)

    ax.bar(datax[idx], datay[idx], width = 5)
plt.subplots_adjust(hspace = 0.5)

Here is the outcome I have:

enter image description here

bests!

Upvotes: 1

Views: 1310

Answers (1)

Glenn Gribble
Glenn Gribble

Reputation: 390

You need a locator instance per axis, see Matplotlib Locator doc:

for idx, ax in enumerate(axs):
    ax.xaxis.set_major_locator(md.YearLocator())
    ax.xaxis.set_major_formatter(years_fmt)
    ax.tick_params(which='major', axis='x', pad=14)
    ax.xaxis.set_minor_locator(md.MonthLocator())
    ax.xaxis.set_minor_formatter(month_fmt)

output

Upvotes: 3

Related Questions