【问题标题】:How to set x-axis in every 10 years如何设置每 10 年的 x 轴
【发布时间】:2020-07-11 04:29:06
【问题描述】:

我对绘制时间序列数据有疑问。我想每 10 年显示一次 x 轴,但我只能每年显示一次。任何人都可以提供解决方案吗??

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)

【问题讨论】:

  • set_major_locator(mdates.YearLocator(10)) docs

标签: matplotlib time-series axis


【解决方案1】:

YearLocator takes an argument base= 指定滴答之间的时间段

示例:

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)

编辑 如果您希望日期以非基数的倍数开始,那么您有两个我能想到的解决方案。

  • 正确的解决方法是听从in this answer的建议
  • 但是,更简单的解决方案是设置年度刻度,但仅显示每个刻度中的一个

代码:

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

【讨论】:

  • 好.. 但我想要的数据范围是从 1962 年到 2019 年,只有每 10 年设置的 x 轴。就像 1960,1970, 1980 ... 2020
  • 我提出了一个有点骇人听闻的解决方案
猜你喜欢
  • 2016-03-19
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多