【发布时间】:2021-05-25 00:18:46
【问题描述】:
我正在尝试绘制一个时间序列,看起来像这样
ts
2020-01-01 00:00:00 1300.0
2020-01-01 01:00:00 1300.0
2020-01-01 02:00:00 1300.0
2020-01-01 03:00:00 1300.0
2020-01-01 04:00:00 1300.0
...
2020-12-31 19:00:00 1300.0
2020-12-31 20:00:00 1300.0
2020-12-31 21:00:00 1300.0
2020-12-31 22:00:00 1300.0
2020-12-31 23:00:00 1300.0
Freq: H, Name: 1, Length: 8784, dtype: float64
我通过以下方式绘制它:ts.plot(label=label, linestyle='--', color='k', alpha=0.75, zorder=2)
如果时间序列ts 从2020-01-01 开始到2020-12-31,当我调用plt.xticks()[0] 时我会得到关注:
array([438288, 439032, 439728, 440472, 441192, 441936, 442656, 443400,
444144, 444864, 445608, 446328, 447071], dtype=int64)
这很好,因为该数组的第一个元素实际上显示了第一个 xtick 的正确位置。但是,当我将时间序列对象从2019-01-01 扩展到2020-12-31 时,两年多来,当我调用plt.xticks()[0] 时,我得到以下信息:
array([429528, 431688, 433872, 436080, 438288, 440472, 442656, 444864,
447071], dtype=int64)
我不明白为什么现在我得到的 xticks 值越来越少。因此,12 个月以来,我为 xticks 获得了 13 个位置。但在 24 个月里,我预计会获得 25 个地点。相反,我只得到了 9 个。我怎样才能得到所有这 25 个位置?
这是整个脚本:
fig, ax = plt.subplots(figsize=(8,4))
ts.plot(label=label, linestyle='--', color='k', alpha=0.75, zorder=2)
locs, labels = plt.xticks()
【问题讨论】:
-
比例有什么区别?我敢打赌,第二个情节每 3 个月就有一次。要获得
25的刻度,请尝试MonthLocator。 -
你是对的。 @QuangHoang 但是,当我使用
ax.xaxis.set_major_locator(mdates.MonthLocator())时,我得到 575 个刻度作为 xticks。
标签: python datetime matplotlib location xticks