首页 > 解决方案 > 将时间序列数据绘制为堆积条形图

问题描述

我有一些时间间隔不相等的时间序列数据。在每个时间点,我都有一些不同类别的价值。我想用表示时间间隔大小的条形宽度绘制这些数据,并用堆叠的条形表示每个不同类别的值。

绘制时,条形的顶部应该看起来像数据总和(跨类别)的阶跃函数。

编辑:添加了 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 或任何其他方法得到答案。

标签: pythonpandasmatplotlibbar-chart

解决方案


您可以将列表导入熊猫数据框以创建 - 您已经提到过 - 步骤功能:

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 ()

输出: 在此处输入图像描述


推荐阅读