0

I'm plotting times along the x-axis, and I want every month to be labeled on minor ticks and the years to be labeled on major ticks so that they're not overlapping. I'm following this method exactly, but I'm not getting the same results. The "Jan" each year isn't showing up above the major ticklabel.

enter image description here

The relevant portion of my code is:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

years=mdates.YearLocator()
months=mdates.MonthLocator()
monthsFmt=mdates.DateFormatter('%b') 
yearsFmt=mdates.DateFormatter('\n\n%Y')  # add some space for the year label
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)

How do I get "Jan" to show on the minor ticklabel in the same time coordinate as the year?

Edit: Not a solution, but a workaround: if I change the location of the major ticks by 20 minutes (datetime.datetime(2018,1,1,0,20,0)) and manually set the ticks and labels, it's effectively the same. Kludgy though. I'm not sure if the 20 minute offset would work on other time ranges, nor did I experiment.

xticks,xticklabels=[],[]
for year in range(minyear,maxyear+1):
    xticks.append(datetime.datetime(year,1,1,0,20,0))
    xticklabels.append(f'\n\n{year}')
ax.set_xticks(xticks)
ax.set_xticklabels(xticklabels)
Joey
  • 53
  • 1
  • 7
  • Maybe this discussion is related: https://github.com/matplotlib/matplotlib/issues/13618#issuecomment-470707928 ? This and other replies contain some ways to try to handle your situation. – JohanC Nov 29 '19 at 06:52
  • You may also want to try ConciseDateformatter which does this with major formatters (except for the vertical offset) – Jody Klymak Nov 29 '19 at 14:40

0 Answers0