[英]Plotting time series data as a stacked bar plot
I have some time series data with unequal time intervals.我有一些时间间隔不相等的时间序列数据。 At each time point, I have some value split across a number of different categories.
在每个时间点,我都有一些不同类别的价值。 I would like to plot this data with the width of the bars representing the size of the time interval, and the bar being stacked to represent the value of each different category.
我想 plot 这个数据用条形的宽度代表时间间隔的大小,而条形被堆叠来代表每个不同类别的值。
When plotted, the tops of the bars should look like a step function of the sum (across categories) of the data.绘制时,条形的顶部应该看起来像数据总和(跨类别)的一步 function。
Edit: added mwe.编辑:添加了 mwe。 For example, if I have 3 categories and 5 time points, my data would consist of a vector t and a matrix x as follows
例如,如果我有 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]]
Edit: This is in Python.编辑:这是在 Python 中。 I'd be happy with an answer using pandas, matplotlib, or any other.
我会很高兴使用 pandas、matplotlib 或任何其他答案。
You can import your lists into a pandas dataframe to create a - you mentioned it already - step function:您可以将列表导入 pandas dataframe 以创建 - 您已经提到过 - 步骤 function:
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 ()
If you wanted to have filled areas, you might want to use fill_between instead:如果你想填充区域,你可能想使用 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 ()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.