python - Matplotlib 以 1 小时为间隔绘制 24 小时图
问题描述
嗨,我目前有这个情节。现在,此图显示每个刻度的间隔为 3 小时。我想要从 0:00 到 23:59 或回到 0:00 的所有时间,即 00:00、01:00、02:00 ... 23:00、23:59 或 00:00。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as md
import pandas as pd
df = pd.DataFrame({'toronto_time': ['2018-09-08 00:00:50',
'2018-09-08 01:01:55',
'2018-09-08 05:02:18',
'2018-09-08 07:05:24',
'2018-09-08 16:05:34',
'2018-09-08 23:06:33'],
'description': ['STATS', 'STATS', 'DEV_OL', 'STATS', 'STATS', 'CMD_ERROR']})
df['toronto_time'] = pd.to_datetime(df['toronto_time'], format='%Y-%m-%d %H:%M:%S')
fig, ax = plt.subplots(figsize=(8,6))
plt.plot('toronto_time', 'description', data=df)
ax.set_xlim(df['toronto_time'].min()-pd.Timedelta(1,'h'),
df['toronto_time'].max()+pd.Timedelta(1,'h'))
ax.xaxis.set_major_formatter(md.DateFormatter('%H:%M:%S'))
plt.show()
解决方案
插入行:
ax.xaxis.set_major_locator(md.HourLocator(interval = 1))
似乎有很大的不同,因为它设置了刻度线频率。
完整示例如下:
import matplotlib.pyplot as plt
import matplotlib.dates as md
import pandas as pd
df = pd.DataFrame({'toronto_time': ['2018-09-08 00:00:50',
'2018-09-08 01:01:55',
'2018-09-08 05:02:18',
'2018-09-08 07:05:24',
'2018-09-08 16:05:34',
'2018-09-08 23:06:33'],
'description': ['STATS', 'STATS', 'DEV_OL', 'STATS', 'STATS',
'CMD_ERROR']})
df['toronto_time'] = pd.to_datetime(df['toronto_time'], format='%Y-%m-%d %H:%M:%S')
fig, ax = plt.subplots(figsize=(8,6))
plt.plot('toronto_time', 'description', data=df)
ax.set_xlim(df['toronto_time'].min()-pd.Timedelta(1,'h'),
df['toronto_time'].max()+pd.Timedelta(1,'h'))
ax.xaxis.set_major_locator(md.HourLocator(interval = 1))
ax.xaxis.set_major_formatter(md.DateFormatter('%H:%M:%S'))
fig.autofmt_xdate()
plt.show()
我还在fig.autofmt_xdate()
之前添加了一行,plt.show()
以帮助格式化每小时频率,以防止 x 轴上的时间戳重叠。
这产生:
推荐阅读
- python - 对项目进行排序但防止相同名称的项目彼此相邻;还在集合中添加随机化
- java - 使用我访问过的节点查找到原点的最短路径的图表
- ignite - 删除 Ignite 表不会从持久层删除数据
- git - Git - 如果我从父分支中删除提交,它是否也会从提交在父分支上时创建的子分支中消失?
- html - Angular ::ng-deep {} 在 *.component.css ng5-slider 中不起作用
- asp.net-core - 在代码部分的组件中使用 foreach 循环中的当前项
- tensorflow - Tensorflow Keras 在训练和验证中的类别数量不同
- reactjs - 如何在子反应组件中拥有反应路由器链接
- javascript - 无法将字段添加到参数对象
- c - 与患者年龄相关的疾病病例数