Pandas - Stacked horizontal barchat for timeline?

2019-06-07 21:46发布

I'm looking at creating a timeline to show state changes for some items.

timeline

For each item, I have a list of events - e.g.:

  • 08:00 - Item A is now in state RED
  • 08:00 - Item B is now in state GREEN
  • 08:55 - Item B is now in state PURPLE
  • 09:00 - Item A is now in state BLUE
  • 09:22 - Item A is now in state YELLOW
  • 10:20 - Item B is now in state RED etc.

I'm using pandas, and was thinking of using the stacked horizontal barcharts (http://pandas.pydata.org/pandas-docs/stable/visualization.html#bar-plots):

pandas stacked horizontal barchart

However, the barchart in this case is backed by a dataframe like this:

In [17]: df2 Out[17]: a b c d 0 0.865681 0.276997 0.691200 0.077541 1 0.863821 0.465361 0.076636 0.013124 2 0.266339 0.359055 0.237709 0.698812 3 0.880864 0.198044 0.807911 0.889326 4 0.253440 0.080855 0.206936 0.603920 5 0.121422 0.880760 0.492782 0.841651 6 0.151359 0.264984 0.249734 0.136582 7 0.222347 0.007675 0.978766 0.267517 8 0.102839 0.847454 0.775913 0.519219 9 0.118314 0.347371 0.314426 0.308254

I'm not sure of the most efficient way in pandas to map my timeline of events into something and plot it. I suppose I could convert the timestamps into duration (e.g. number of seconds), but I'd prefer the x-axis to display timestamps as per the first example above, so that may not work.

Is there a better of doing this?

1条回答
仙女界的扛把子
2楼-- · 2019-06-07 21:58
fig, ax = plt.subplots()
df.plot(kind='barh', stacked=True, ax=ax)
ax.set_yticklabels(['A', 'B', 'C', 'D', 'E', 'F'])
time = pd.date_range(start=pd.to_datetime('07:00', format='%H:%M'), end=pd.to_datetime('13:00', format='%H:%M'),freq='H')
time_x = [dt.strftime('%H:%M') for dt in time]
ax.set_xticklabels(time_x)
fig.autofmt_xdate()
plt.show()

enter image description here

查看更多
登录 后发表回答