[英]Matplotlib change x-axis unit
目前,我正在使用 matplotlib 绘制 pandas 的图表。 但是当我绘制时,我得到了结果图表的 x 轴,以数月为单位。 我想将其更改为每天和每小时。 我怎样才能实现它?
我的数据集:
Recorded Time Count
2019-08-01 00:10:00 3
2019-08-01 00:20:00 5
2019-08-01 00:30:00 0
2019-08-01 00:40:00 5
2019-08-01 00:50:00 9
and so on...
获取索引:
people = people.set_index('Recorded Time')
people.index
这里的人是熊猫数据框
索引输出:
DatetimeIndex(['2019-08-01 00:10:00', '2019-08-01 00:20:00',
'2019-08-01 00:30:00', '2019-08-01 00:40:00',
'2019-08-01 00:50:00', '2019-08-01 01:00:00',
'2019-08-01 01:10:00', '2019-08-01 01:20:00',
'2019-08-01 01:30:00', '2019-08-01 01:40:00',
...
'2019-12-17 19:50:00', '2019-12-17 20:00:00',
'2019-12-17 20:10:00', '2019-12-17 20:20:00',
'2019-12-17 20:30:00', '2019-12-17 20:40:00',
'2019-12-17 20:50:00', '2019-12-17 21:00:00',
'2019-12-17 21:10:00', '2019-12-17 21:20:00'],
dtype='datetime64[ns]', name='Recorded Time', length=20000, freq=None)
意思:
y = people['Count'].resample(rule='24H').mean()
平均输出
Recorded Time
2019-08-01 37.384615
2019-08-02 35.805556
2019-08-03 34.298611
2019-08-04 36.833333
2019-08-05 35.340278
2019-08-06 36.854167
2019-08-07 35.180556
2019-08-08 35.979167
2019-08-09 34.847222
2019-08-10 36.381944
2019-08-11 36.006944
2019-08-12 35.041667
2019-08-13 36.201389
2019-08-14 35.291667
2019-08-15 35.041667
2019-08-16 34.944444
2019-08-17 35.826389
2019-08-18 37.347222
2019-08-19 34.312500
2019-08-20 33.472222
2019-08-21 33.743056
2019-08-22 35.243056
2019-08-23 36.819444
2019-08-24 35.145833
2019-08-25 35.069444
2019-08-26 33.875000
2019-08-27 35.111111
2019-08-28 34.590278
2019-08-29 35.826389
2019-08-30 36.381944
...
2019-11-18 34.395833
2019-11-19 35.527778
2019-11-20 35.798611
2019-11-21 34.361111
2019-11-22 36.062500
2019-11-23 35.298611
2019-11-24 34.187500
2019-11-25 35.020833
2019-11-26 34.465278
2019-11-27 35.729167
2019-11-28 34.715278
2019-11-29 34.173611
2019-11-30 34.812500
2019-12-01 39.638889
2019-12-02 35.000000
2019-12-03 36.479167
2019-12-04 35.868056
2019-12-05 34.798611
2019-12-06 37.916667
2019-12-07 33.972222
2019-12-08 32.958333
2019-12-09 35.361111
2019-12-10 35.673611
2019-12-11 35.041667
2019-12-12 36.965278
2019-12-13 35.805556
2019-12-14 36.638889
2019-12-15 36.027778
2019-12-16 36.263889
2019-12-17 38.558140
Freq: 24H, Name: Count, Length: 139, dtype: float64
最后,绘制数据:
y.plot(figsize=(15, 6))
plt.show()
您应该能够更改 xaxis 上的 DateFormatter。
from matplotlib.dates import DateFormatter
myFmt = DateFormatter("%d") # Day format
ax.xaxis.set_major_formatter(myFmt)
fig.autofmt_xdate()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.