3
rcParams['date.autoformatter.month'] = "%b\n%Y"

I am using matpltolib to plot a time-series and if I set rcParams as above, the resulting plot has month name and year labeled at each tick. How can I set it up so that year is only plotted at january of each year. I tried doing this, but it does not work:

rcParams['date.autoformatter.month'] = "%b"
rcParams['date.autoformatter.year'] = "%Y"
3
  • How long is your time series? If you have your x tick labels you could try a find and replace such that every January would include the year. Commented Apr 9, 2018 at 4:43
  • the time-series can span upto 2 years. However, that approach sounds hacky Commented Apr 9, 2018 at 4:46
  • I don't believe you will be able to get what you want without a hacky approach. Commented Apr 9, 2018 at 4:48

1 Answer 1

8

The formatters do not allow to specify conditions on them. Depending on the span of the series, the AutoDateFormatter will either fall into the date.autoformatter.month range or the date.autoformatter.year range.

Also, the AutoDateLocator may not necessarily decide to actually tick the first of January at all.

I would hence suggest to specify the tickers directly to the desired format and locations. You may use the major ticks to show the years and the minor ticks to show the months. The format for the major ticks can then get a line break, in order not to overlap with the minor ticklabels.

import matplotlib.pyplot as plt
import matplotlib.dates
from datetime import datetime

t = [datetime(2016,1,1), datetime(2017,12,31)]
x = [0,1]

fig, ax = plt.subplots()
ax.plot(t,x)

ax.xaxis.set_major_locator(matplotlib.dates.YearLocator())
ax.xaxis.set_minor_locator(matplotlib.dates.MonthLocator((1,4,7,10)))

ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("\n%Y"))
ax.xaxis.set_minor_formatter(matplotlib.dates.DateFormatter("%b"))
plt.setp(ax.get_xticklabels(), rotation=0, ha="center")

plt.show()

enter image description here

You could then also adapt the minor ticks' lengths to match those of the major ones in case that is desired,

ax.tick_params(axis="x", which="both", length=4)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.