You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Matplotlib构建请求量与时间戳(HH:MM)统计图?

没问题,我来帮你搞定这个请求量时间趋势图的绘制!针对你提到的需求——展示早6点到晚6点的请求模式,我们可以分步骤实现,确保图表清晰直观:

第一步:数据预处理

首先,原始的时间戳是HH:MM格式的字符串,Matplotlib没法直接按时间顺序处理,所以得先把它们转换成datetime对象。另外如果你的500条数据里有超出6:00-18:00范围的记录,也可以提前筛选掉,避免干扰图表展示。

第二步:绘图与美化

接下来就可以用Matplotlib绘图了,推荐用折线图来展示趋势(如果想突出每个时间点的具体数值,也可以用柱状图)。重点要调整X轴的刻度格式,避免时间标签拥挤重叠,同时设置合理的刻度间隔,比如每小时显示一个刻度。

完整代码示例

这里给你两种场景的代码:

场景1:已有每个时间点的请求数(如你提供的示例数据)

import matplotlib.pyplot as plt
from datetime import datetime
from matplotlib.dates import HourLocator

# 替换成你的实际500条数据
time_stamp = ['06:02', '06:03', '06:12', '06:16', '06:17', '06:27', '06:28', '06:30', '06:31', '06:34', '06:35', '06:36', '06:37', '06:38', '06:39', '06:40', '06:41', '06:42', '06:43']
requests = [74, 20, 2, 1, 11, 9, 34, 15, 8, 5, 12, 18, 22, 19, 14, 10, 7, 5, 3]

# 转换时间格式并筛选时间范围
time_objects = [datetime.strptime(ts, '%H:%M') for ts in time_stamp]
start_time = datetime.strptime('06:00', '%H:%M')
end_time = datetime.strptime('18:00', '%H:%M')

filtered_times = []
filtered_requests = []
for t, req in zip(time_objects, requests):
    if start_time <= t <= end_time:
        filtered_times.append(t)
        filtered_requests.append(req)

# 创建图表
plt.figure(figsize=(12, 6))
plt.plot(filtered_times, filtered_requests, marker='o', linestyle='-', color='#1f77b4', label='请求数量')

# 设置X轴格式
plt.gcf().autofmt_xdate()  # 自动旋转X轴标签避免重叠
date_formatter = plt.matplotlib.dates.DateFormatter('%H:%M')
plt.gca().xaxis.set_major_formatter(date_formatter)
plt.gca().xaxis.set_major_locator(HourLocator(interval=1))  # 每小时显示一个刻度

# 添加标题和标签
plt.title('6:00-18:00 请求数量时间趋势图', fontsize=14, pad=15)
plt.xlabel('时间 (HH:MM)', fontsize=12)
plt.ylabel('请求数量', fontsize=12)
plt.grid(True, linestyle='--', alpha=0.7)
plt.legend()

plt.tight_layout()
plt.show()

场景2:原始数据是每条请求对应一个时间戳(需先统计数量)

如果你的500条数据是单条请求的时间记录,那需要先按分钟分组统计请求数,推荐用Pandas来简化操作:

import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.dates import HourLocator

# 示例:500条请求的时间戳列表
time_stamp = ['06:02', '06:02', '06:03', ...]  # 替换成你的实际数据

# 转换为DataFrame并统计
df = pd.DataFrame({'time': time_stamp})
df['time'] = pd.to_datetime(df['time'], format='%H:%M')

# 筛选6:00-18:00的数据
df = df[(df['time'] >= '06:00') & (df['time'] <= '18:00')]

# 按分钟分组统计请求数
grouped_df = df.groupby(df['time'].dt.strftime('%H:%M')).size().reset_index(name='requests')
# 把时间转回datetime对象用于绘图
grouped_df['time'] = pd.to_datetime(grouped_df['time'], format='%H:%M')

# 绘图
plt.figure(figsize=(12, 6))
plt.plot(grouped_df['time'], grouped_df['requests'], marker='o', linestyle='-', color='#ff7f0e', label='请求数量')

# 设置X轴格式
plt.gcf().autofmt_xdate()
date_formatter = plt.matplotlib.dates.DateFormatter('%H:%M')
plt.gca().xaxis.set_major_formatter(date_formatter)
plt.gca().xaxis.set_major_locator(HourLocator(interval=1))

plt.title('6:00-18:00 请求数量时间趋势图', fontsize=14, pad=15)
plt.xlabel('时间 (HH:MM)', fontsize=12)
plt.ylabel('请求数量', fontsize=12)
plt.grid(True, linestyle='--', alpha=0.7)
plt.legend()

plt.tight_layout()
plt.show()

额外提示

  • 如果X轴标签还是拥挤,可以调整figsize的宽度,或者设置plt.xticks(rotation=45)来进一步旋转标签。
  • 可以根据需求把折线图换成柱状图(把plt.plot改成plt.bar),更适合对比每个时间点的请求量差异。

内容的提问来源于stack exchange,提问作者saurav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:35:22