python - 将时间序列数据绘制为堆积条形图
问题描述
我有一些时间间隔不相等的时间序列数据。在每个时间点,我都有一些不同类别的价值。我想用表示时间间隔大小的条形宽度绘制这些数据,并用堆叠的条形表示每个不同类别的值。
绘制时,条形的顶部应该看起来像数据总和(跨类别)的阶跃函数。
编辑:添加了 mwe。例如,如果我有 3 个类别和 5 个时间点,我的数据将由一个向量 t 和一个矩阵 x 组成,如下所示
t = [0, 0.1, 0.2, 0.5, 1]
x = [[1, 1, 1, 2, 3], [1, 0, 1, 3, 5], [2, 3, 4, 4, 2]]
编辑:这是在 Python 中。我很乐意使用 pandas、matplotlib 或任何其他方法得到答案。
解决方案
您可以将列表导入熊猫数据框以创建 - 您已经提到过 - 步骤功能:
import matplotlib.pyplot as plt
import pandas as pd
t = [0, 0.1, 0.2, 0.5, 1]
x = [[1, 1, 1, 2, 3], [1, 0, 1, 3, 5], [2, 3, 4, 4, 2]]
df = pd.DataFrame(x).T
df.index = t
df.columns = list("ABC")
df = df.cumsum(axis=1)
df.plot(drawstyle="steps-mid")
plt.xticks(df.index)
plt.ylim(0)
plt.show ()
如果你想填充区域,你可能想使用 fill_between 代替:
import matplotlib.pyplot as plt
import pandas as pd
t = [0, 0.1, 0.2, 0.5, 1]
x = [[1, 1, 1, 2, 3], [1, 0, 1, 3, 5], [2, 3, 4, 4, 2]]
df = pd.DataFrame(x).T
df.index = t
df.columns = list("ABC")
df = df.cumsum(axis=1)
for y2, y1 in zip(df.columns[::-1], df.columns[1::-1]):
plt.fill_between(df.index, df[y1], df[y2], step="mid", alpha=0.7, label=y2)
plt.fill_between(df.index, 0, df[y1], step="mid", alpha=0.7, label=y1)
plt.xticks(df.index)
plt.legend()
plt.show ()
推荐阅读
- python - sys.setrecursionlimit 在 jupyter 笔记本中不起作用
- node.js - 以编程方式更新 node_modules 以匹配 package.json 版本?
- node.js - Mongoose/MongoDB PUT:如果对象 ID 在数组中是唯一的,则将对象推送到数组
- python - 问题标记 POS
- ios - 即使 App 被 IOS 中的用户杀死,如何每 10 秒调用一次 api?
- javascript - jquery val() 不会改变值
- linux - 线程“主”java.lang.UnsatisfiedLinkError 中的异常:java.library.path 中没有 dbjdbc17
- javascript - 在处理同一父元素的多次出现时,如何定位正确的数据属性和子元素?
- javascript - 添加图像 - ReactJS
- microsoft-teams - 从 Teams 中的对话中获取显示状态