如何解决matplotlib xticks 输出错误的数组
我正在尝试绘制一个时间序列,看起来像这样
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
时,超过 2 年,当我调用 plt.xticks()[0]
时,我得到以下信息:
array([429528,431688,433872,436080,438288,dtype=int64)
我不明白为什么现在我得到的 xticks 值越来越少。因此,在 12 个月内,我获得了 13 个 xticks 位置。但是在 24 个月的时间里,我一直希望能有 25 个地点。相反,我只有 9 个。我如何才能获得所有这 25 个位置?
这是整个脚本:
fig,ax = plt.subplots(figsize=(8,4))
ts.plot(label=label,zorder=2)
locs,labels = plt.xticks()
解决方法
Matplotlib 会自动选择适当数量的刻度和刻度标签,以便 x 轴不会变得不可读。您可以使用 matplotlib.dates
模块中的刻度定位器和格式化程序来覆盖默认行为。
但请注意,您正在使用 pandas plot method 绘制时间序列,custom tick formatters for time series plots 是 plt.plot
的包装器。 Pandas 使用 matplotlib date units 生成格式良好的刻度标签。通过这样做,它对不同于 undocumented 的日期使用 x 轴单位,这解释了为什么当您尝试使用 MonthLocator
时会得到看起来像随机数的刻度。
要使熊猫图与 matplotlib.dates
刻度定位器兼容,您需要添加 x_compat=True
参数。不幸的是,这也删除了熊猫自定义刻度标签格式化程序。因此,这里是一个示例,说明如何使用带有熊猫图的 matplotlib 日期刻度定位器并获得类似刻度格式(不包括小刻度):
import pandas as pd # v 1.1.3
import matplotlib.pyplot as plt # v 3.3.2
import matplotlib.dates as mdates
# Create sample time series stored in a dataframe
ts = pd.DataFrame(data=dict(constant=1),index=pd.date_range('2019-01-01','2020-12-31',freq='H'))
# Create pandas plot
ax = ts.plot(figsize=(10,4),x_compat=True)
ax.set_xlim(min(ts.index),max(ts.index))
# Select and format x ticks
ax.xaxis.set_major_locator(mdates.MonthLocator())
ticks = pd.to_datetime(ax.get_xticks(),unit='d') # timestamps of x ticks
labels = [timestamp.strftime('%b\n%Y') if timestamp.year != ticks[idx-1].year
else timestamp.strftime('%b') for idx,timestamp in enumerate(ticks)]
plt.xticks(ticks,labels,rotation=0,ha='center');
{{3}}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。