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

基于时间有序字典生成多时间步区间统计直方图的技术咨询

实现方法

数据预处理与区间统计

先把时间序列字典转换成结构化数据,再定义无重叠的区间规则,最后统计每个时间步的区间数值数量:

import pandas as pd
import matplotlib.pyplot as plt

# 示例时间序列字典(替换为你的实际数据)
time_dict = {
    "t1": {"k1": -0.5, "k2": 0.008, "k3": 0.05, "k4": 0.8, "k5": 7, "k6": 50},
    "t2": {"m1": -2, "m2": 0.012, "m3": 0.2, "m4": 2, "m5": 15, "m6": 80},
    "t3": {"n1": 0, "n2": 0.003, "n3": 0.09, "n4": 5, "n5": 20, "n6": 90}
}

# 转换为DataFrame格式,方便后续处理
data = []
for timestamp, sub_dict in time_dict.items():
    for val in sub_dict.values():
        data.append({"timestamp": timestamp, "value": val})
df = pd.DataFrame(data)

# 定义区间边界和对应标签(确保无重叠)
bins = [-float('inf'), 0, 0.01, 0.1, 1, 10, 100]
labels = ["<0", "0-0.01", "0.01-0.1", "0.1-1", "1-10", "10-100"]

# 划分区间并按时间步+区间统计数量
df["interval"] = pd.cut(df["value"], bins=bins, labels=labels, include_lowest=True)
count_result = df.groupby(["timestamp", "interval"]).size().unstack(fill_value=0)

绘制多子图直方图

根据时间步数量布局子图,每个子图对应一个时间步的区间分布:

# 计算子图行列数(可根据时间步总数调整列数)
total_timestamps = len(count_result.index)
cols = 2
rows = (total_timestamps + cols - 1) // cols

# 创建画布并逐个绘制子图
plt.figure(figsize=(cols*6, rows*4))
for idx, timestamp in enumerate(count_result.index, 1):
    ax = plt.subplot(rows, cols, idx)
    count_result.loc[timestamp].plot(kind="bar", ax=ax, color="#2ca02c")
    ax.set_title(f"时间步: {timestamp}")
    ax.set_xlabel("数值区间")
    ax.set_ylabel("数量")
    ax.tick_params(axis='x', rotation=45)

plt.tight_layout()
plt.show()

关键注意点

  • 区间必须按无重叠顺序定义,否则统计结果会出错,这里把<0放在最前,后续区间采用左闭右开规则
  • 如果你的时间戳是可排序的字符串/数字,count_result会自动保留原时间顺序
  • 可通过调整cols、画布尺寸、配色等参数,让图表更贴合你需要的样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:15:50