Matplotlib to manipulate dates to every 12 months

I draw a figure where the default format is displayed as:

An annual tick appears every 12 months, but months show only every 3 months

I would like to change it so that monthly ticks appear every 1 month, but save a year. My current attempt:

years = mdates.YearLocator() months = mdates.MonthLocator() monthsFmt = mdates.DateFormatter('%b-%y') dts = s.index.to_pydatetime() fig = plt.figure(); ax = fig.add_subplot(111) ax.plot(dts, s) ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(monthsFmt) 

but this does not give the correct result:

Wrong

How exactly do I need to change it so that it appears as the first, but with months of ticks appear every month?

+5
source share
1 answer

One solution has been identified that should stick for months to minor ticks and keep the years as the main one.

eg.

 years = mdates.YearLocator() months = mdates.MonthLocator() monthsFmt = mdates.DateFormatter('%b') yearsFmt = mdates.DateFormatter('\n\n%Y') # add some space for the year label dts = s.index.to_pydatetime() fig = plt.figure(); ax = fig.add_subplot(111) ax.plot(dts, s) ax.xaxis.set_minor_locator(months) ax.xaxis.set_minor_formatter(monthsFmt) plt.setp(ax.xaxis.get_minorticklabels(), rotation=90) ax.xaxis.set_major_locator(years) ax.xaxis.set_major_formatter(yearsFmt) 

Results in: enter image description here

+7
source

Source: https://habr.com/ru/post/1243002/


All Articles