如何使用 matplotlib 获取甘特图
Posted
技术标签:
【中文标题】如何使用 matplotlib 获取甘特图【英文标题】:How to get gantt plot using matplotlib 【发布时间】:2017-09-08 03:00:27 【问题描述】:我得到了一些数据,例如:
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
,而不是那么小(微秒)的大小。
请告诉我该怎么做?
【问题讨论】:
您的数据中有 4 列。目前尚不清楚它们应如何排列在图表中。请通过edit提出您的问题添加信息。 其实列名可以是Task、Start、Finish、Resource单独如 甘特图。 【参考方案1】:为了在 matplotlib 中生成甘特图,可以使用plt.broken_barh
函数。 matplotlib 页面上有a broken_barh
example。
为了对数据进行过滤和分组,可以使用 pandas,尤其是数据框的 groupby
函数。
这是一个完整的例子:
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()
产生以下情节:
【讨论】:
谢谢!这很有帮助。在 groupby 之后,您将如何更改 y 轴上对象的顺序?这对我的项目非常重要。以上是关于如何使用 matplotlib 获取甘特图的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 matplotlib 自定义甘特图并在图表上显示指示当前时间的垂直线?
如何使用 Python Pandas 绘制堆叠事件持续时间(甘特图)
MATLAB | 如何使用MATLAB绘制甘特图(gantt chart)