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

使用matplotlib绘制等时间间隔统计的实验数量区间柱状图

等时间间隔分组统计绘图实现方案

你需要实现的是耗时字段的等距分箱频次统计+柱状图绘制,基于pandas和matplotlib可直接完成,核心步骤如下:

  • 配置分箱参数:指定时间步长、耗时列对应的列名
  • 生成分箱边界:从0(或你需要的起始值)开始,按步长生成覆盖耗时最大值的区间边界点
  • 分箱计数:用pd.cut给每条数据打上所属区间标签,再统计每个区间的样本总量
  • 绘图展示:用柱状图可视化区间和对应数量的关系

完整代码示例

假设你的DataFrame变量名为df,存储耗时的列名为time_cost(替换成你表中实际的列名即可):

import pandas as pd
import matplotlib.pyplot as plt

# 基础配置
step_length = 20  # 等间隔步长
cost_column = "time_cost"  # 替换为实际的耗时列名

# 生成分箱边界
max_cost = df[cost_column].max()
bins = list(range(0, int(max_cost) + step_length + 1, step_length))

# 分箱并统计每个区间的实验数量
# right=False对应区间规则为[0,20)、[20,40)...,即数值20归入20-40区间
df["time_interval"] = pd.cut(df[cost_column], bins=bins, right=False)
interval_counts = df["time_interval"].value_counts().sort_index()

# 绘制柱状图
plt.figure(figsize=(10, 6))
interval_counts.plot(kind="bar", edgecolor="black")
plt.xlabel("耗时区间")
plt.ylabel("实验总数量")
plt.title("耗时区间实验数量分布")
plt.xticks(rotation=0)
plt.tight_layout()
plt.show()

区间规则调整

如果要严格匹配你提到的「0-20、21-40」划分逻辑(即数值20归入0-20区间,21-40的数值归入下一个区间),只需要修改分箱参数即可:

# 调整分箱开闭规则,对应区间为(0,20]、(20,40]...
df["time_interval"] = pd.cut(df[cost_column], bins=bins, right=True)

后续统计和绘图逻辑不需要改动。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 09:54:22