甘特图(Gantt chart)又称为横道图、条状图(Bar chart)。
其通过条状图来显示项目、进度和其他时间相关的系统进展的内在关系随着时间进展的情况。
以提出者亨利·劳伦斯·甘特(Henry Laurence Gantt)先生的名字命名
python 绘制甘特图有多种方法,本文做个总结
barh 方式
matplotlib 中的 barh 可以绘制横向矩形框
def barh(y, width, height=0.8, left=None, *, align='center', **kwargs):参数说明
y:纵坐标
left:横坐标,表示 矩形框 最左侧的 x 坐标
width:矩形框的 宽度
height:矩形框的 高度
edgecolor:表示矩形块的边的颜色,通常设置为 black
color:表示矩形块的颜色
示例代码
import matplotlib.pylab as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 显示中文标签
complete_time = {(0, 0, 1, 1): (8, 9, 1),
(8, 1, 2, 1): (11, 13, 2)}
color = ['g', 'r']
for k, v in complete_time.items():
plt.barh(y=k[2], width=v[2], height=0.3, left=v[0], edgecolor="black", color=color[k[1]])
plt.text(v[0] + 0.1, k[2] + 0.1, str(k[1] + 1) + " " + str(k[0] + 1)) # 1 1
plt.text(v[0] + 0.2, k[2] - 0.1, str(v[0]) + " " + str(v[1])) # 8 9
plt.show()输出

更多信息见参考资料
plotly 方式
这是一个独立的包,需要安装 pip install plotly
绘制甘特图的函数为 Plotly.figure_factoryz 中 create_gantt 方法
通过参数事件Task,开始Start,结束Finish的时间的数据来绘制甘特图
import plotly as py
import plotly.figure_factory as ff
pyplt = py.offline.plot
### test1
df = [dict(Task = "项目1", Start = '2019-02-01', Finish = '2019-05-28'),
dict(Task = "项目2", Start = '2019-03-05', Finish = '2019-04-15'),
dict(Task = "项目3", Start = '2019-03-20', Finish = '2019-05-30')]
fig = ff.create_gantt(df)
pyplt(fig, filename='t1.html') # 貌似只能存为 html 文件输出

更多信息见参考资料
推荐方式1,更 pythonic
参考资料:
Python绘制甘特图 barh
Python使用 Plotly 绘制甘特图
https://zhuanlan.zhihu.com/p/341971464 Plotly
















