使用matplotlib和pandas创建事件的时间曲线

2024-06-16 18:24:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个虚线图,表示每个散列的事件长度。我的数据帧如下:

                            hash    event        start          end
0174FAA018E7FAE1E84469ADC34EF666 baseball 00:00:00:000 00:00:00:500
0174FAA018E7FAE1E84469ADC34EF666 baseball 00:00:01:000 00:00:01:500
0174FAA018E7FAE1E84469ADC34EF666 cat      00:00:01:500 00:00:02:500
AF4BB75F98579B8C9F95EABEC1BDD988 baseball 00:00:01:000 00:00:01:500
AF4BB75F98579B8C9F95EABEC1BDD988 cat      00:00:01:500 00:00:02:500
AF4BB75F98579B8C9F95EABEC1BDD988 cat      00:00:03:200 00:00:05:250
AF4BB75F98579B8C9F95EABEC1BDD988 cat      00:00:03:000 00:00:04:350

类似于这里的答案:Change spacing of dashes in dashed line in matplotlib 其中,哈希在y轴上,时间间隔在x轴上,事件类型用颜色编码,如果该时间间隔内没有事件,则用空格分隔。在

这是我迄今为止尝试过的方法,但效果不佳:

^{pr2}$

示例见下文

garbage hand-drawn graph


Tags: 数据答案inevent间隔时间事件hash
1条回答
网友
1楼 · 发布于 2024-06-16 18:24:46

首先,我想说:我与您的请求的第一个关联是matplotlib的broken_barh函数。但到目前为止,我还不知道如何绘制时间增量,因为这在那里是必要的。您的绘图也可以用plot完成,所以我有一些带有if False: (attempt with plt.broken_barh) else (plt.plot-version)结构的代码。看看你自己。
一旦我知道如何在matplotlib中绘制timedelta,我将尝试更新字面上的中断部分。。。在

下面是我希望能帮助你的代码:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from io import StringIO


def brk_str(s):       # just for nicer labeling with such long hashes
    return '\n'.join([s[8*i:8*(i+1)] for i in range(4)])


s = '''                            hash    event        start          end
0174FAA018E7FAE1E84469ADC34EF666 baseball 00:00:00:000 00:00:00:500
0174FAA018E7FAE1E84469ADC34EF666 baseball 00:00:01:000 00:00:01:500
0174FAA018E7FAE1E84469ADC34EF666 cat      00:00:01:500 00:00:02:500
AF4BB75F98579B8C9F95EABEC1BDD988 baseball 00:00:01:000 00:00:01:500
AF4BB75F98579B8C9F95EABEC1BDD988 cat      00:00:01:500 00:00:02:500
AF4BB75F98579B8C9F95EABEC1BDD988 cat      00:00:03:200 00:00:05:250
AF4BB75F98579B8C9F95EABEC1BDD988 cat      00:00:03:000 00:00:04:350'''

df = pd.read_table(StringIO(s), sep='\s+')

df['start'] = pd.to_datetime(df['start'], format='%H:%M:%S:%f')
df['end'] = pd.to_datetime(df['end'], format='%H:%M:%S:%f')

df['dur'] = (df['end'] - df['start'])   # this is only needed in case of broken_barh would work...

e_grpd = df.groupby('event')

fig, ax = plt.subplots()

for i, (e, ev) in enumerate(e_grpd):   # iterate over all events, providing a counter i, the name of every event e and its data ev
    last_color = None    # setting color value to None which means automatically cycle to another color
    for k, (h, hv)in enumerate(ev.groupby('hash')):   # iterate over all hashes, providing a counter k, every hash h and its data hv
        if False:   # desperately not deleting this as broken_barh would save the innermost loop and would generally fit better I think...
            pass
            #ax.broken_barh(ev[['start', 'dur']].T, np.array([i*np.ones(len(ev))+k/10, .1*np.ones(len(ev))]).T)
        else:
            for n, (a, b) in enumerate(zip(hv.start, hv.end)):   # iterate over every single event per hash, providing a counter n and start and stop time a and b
                p = ax.plot([a, b], k*np.ones(2)+i/10, color=last_color, lw=15, label='_' if k>0 or n>0 else '' + e)
                last_color = p[0].get_c()    # setting color value to the last one used to prevent color cycling


ax.set_yticks(range(len(df.groupby('hash').groups)))
ax.set_yticklabels(map(brk_str, df.groupby('hash').groups))
ax.legend(ncol=2, bbox_to_anchor=[0, 0, 1, 1.1], loc=9, edgecolor='w')
plt.tight_layout()

结果为plt.plot

enter image description here

相关问题 更多 >