Issue
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.
When plotted, the tops of the bars should look like a step function of the sum (across categories) of the data.
Edit: added 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
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. I'd be happy with an answer using pandas, matplotlib, or any other.
Solution
You can import your lists into a pandas dataframe to create a - you mentioned it already - step 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:
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 ()
Answered By - Mr. T
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.