Reputation: 101
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)
Upvotes: 2
Views: 2583
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)
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.
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
Upvotes: 3