如何使用Matplotlib获取甘特图 [英] How to get gantt plot using matplotlib

查看:180
本文介绍了如何使用Matplotlib获取甘特图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了一些数据,例如:

I got a number of data like:

a0:86:c6:52:4e:e8,0.006568,0.006620,Out
a0:86:c6:52:4e:e8,0.006663,0.006695,In
a0:86:c6:52:4e:e8,0.008089,0.008141,Out
a0:86:c6:52:4e:e8,0.008185,0.008217,In
01:00:5e:00:00:fb,0.033096,0.035016,Out
33:33:00:00:00:fb,0.034997,0.037077,Out
01:00:5e:7f:ff:fa,0.039969,0.042057,Out
ff:ff:ff:ff:ff:ff,0.059823,0.061639,Out
a0:86:c6:52:4e:e8,0.068865,0.068917,Out
a0:86:c6:52:4e:e8,0.068962,0.068994,In
a0:86:c6:52:4e:e8,0.083492,0.083544,Out
a0:86:c6:52:4e:e8,0.083588,0.083620,In
...

实际上,它可持续120秒.我想使用matplotlib将这些数据绘制成类似甘特图的图形. 原因是大多数甘特图api仅支持时间格式YY-MM-DD HH:MM:SS,而不支持这么小的(微秒)大小.

Actually, it lasts for 120 seconds. And I want to plot these data to something like a gantt graph using matplotlib. The reason is that most gantt chart api only support time format YY-MM-DD HH:MM:SS, and not in so small (microsecond) size.

请告诉我该怎么做?

推荐答案

为了在matplotlib中生成甘特图,可以使用一个broken_barh示例.

In order to produce a Gantt chart in matplotlib, one may use the plt.broken_barh function. There is a broken_barh example on the matplotlib page.

为了过滤和分组数据,可以使用熊猫,尤其是数据框的groupby功能.

In order to filter and group the data, one can use pandas, especially the groupby function of a dataframe.

这是一个完整的示例:

inp = u"""a0:86:c6:52:4e:e8,0.006568,0.006620,Out
a0:86:c6:52:4e:e8,0.006663,0.006695,In
a0:86:c6:52:4e:e8,0.008089,0.008141,Out
a0:86:c6:52:4e:e8,0.008185,0.008217,In
01:00:5e:00:00:fb,0.033096,0.035016,Out
33:33:00:00:00:fb,0.034997,0.037077,Out
01:00:5e:7f:ff:fa,0.039969,0.042057,Out
ff:ff:ff:ff:ff:ff,0.059823,0.061639,Out
a0:86:c6:52:4e:e8,0.068865,0.068917,Out
a0:86:c6:52:4e:e8,0.068962,0.068994,In
a0:86:c6:52:4e:e8,0.083492,0.083544,Out
a0:86:c6:52:4e:e8,0.083588,0.083620,In"""

import pandas as pd
import io
import matplotlib.pyplot as plt

df = pd.read_csv(io.StringIO(inp), header=None, names=["Task", "Start", "Finish", "Resource"] )
df["Diff"] = df.Finish - df.Start

color = {"In":"turquoise", "Out":"crimson"}
fig,ax=plt.subplots(figsize=(6,3))

labels=[]
for i, task in enumerate(df.groupby("Task")):
    labels.append(task[0])
    for r in task[1].groupby("Resource"):
        data = r[1][["Start", "Diff"]]
        ax.broken_barh(data.values, (i-0.4,0.8), color=color[r[0]] )

ax.set_yticks(range(len(labels)))
ax.set_yticklabels(labels) 
ax.set_xlabel("time [ms]")
plt.tight_layout()       
plt.show()

这将产生以下情节:

这篇关于如何使用Matplotlib获取甘特图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆