M.Fajrul Haqqi
M.Fajrul Haqqi

Reputation: 101

How to set x-axis in every 10 years

i have a problem with plot time series data. I want show x-axis in every 10 years but I can only display it every year. Anyone can provide a solution about this??

fig,ax = plt.subplots(figsize=(11,4))
ax.plot(t, data, '0.1', label ='Data')
ax.plot(t, df_filt, 'C1', label='Lowpass Filter, cutoff=50 days')
ax.set_ylabel('Length of Day')
ax.set_xlabel('Time')
ax.legend()
ax.xaxis.set_major_locator(mdates.YearLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
ax.grid(True)

enter image description here

Upvotes: 2

Views: 2583

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40737

YearLocator takes an argument base= to specify the period between ticks

example:

import matplotlib.dates as mdates
t = mdates.drange(mdates.datetime.date(1900,1,1), mdates.datetime.date(2020,12,31), delta=mdates.datetime.timedelta(days=365))
data = np.random.random(size=t.shape)

fig, ax = plt.subplots()
ax.plot(t, data, '0.1', label ='Data')
ax.set_ylabel('Length of Day')
ax.set_xlabel('Time')
ax.legend()
ax.xaxis.set_major_locator(mdates.YearLocator(base=10))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
ax.grid(True)

enter image description here

EDIT if you want the dates to start on a non multiple of the base, then you have two solutions that I can think of.

  • The correct solution is to follow the advice in this answer
  • But, a simpler solution could be to set yearly ticks, but only display one out of every tick

code:

ax.xaxis.set_major_locator(mdates.YearLocator(base=1))
ax.margins(x=0) # so that the axis starts at the minimum date
ax.set_xticks(ax.get_xticks()[::10]) # only show one every 10 years

enter image description here

Upvotes: 3

Related Questions