python绘制甘特图代码

python绘制甘特图

一个任务中有3个步骤,每个步骤的时间写在timetables中,以下t1、t2相同是因为该场景是t2和t3是一样的。

# coding=utf-8
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np

plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
t2=0.6
t1=1.8
timetables = [[[9, t1,t2], [9, t1, t2], [9,t1, t2], [9, t1, t2], [9, t1, t2]],          # 不缓存
              [[0.1, t1, t2], [1.8, t1, t2], [1.8, t1, t2], [1.8, t1,t2], [1.8, t1,t2]],  # 均摊缓存了37.7
              [[0.1, t1,t2], [0.1, t1,t2], [0.1, t1, t2], [0.1, t1,t2], [6.9, t1,t2]]]      # 缓存了3.4

plt.figure(figsize=(20, 14), dpi=100)
plt.title("任务流水甘特图", fontsize=30)
for t, timetable in enumerate(timetables):
    add = []
    left = []
    plt.subplot(len(timetables), 1, t + 1)  # 两行两列,这是第四个图
    for i in range(len(timetable)):
        add.append(timetable[i])
        if i == 0:
            cur_left = [0, timetable[0][0], timetable[0][0] + timetable[0][1]]
        else:
            cur_left = [max(left[i - 1][0] + add[i - 1][0],left[i - 1][1]+add[i-1][1] - add[i][0]),
                        # max(本batch的load_start+load_time,上一个batch的augstart+aug)
                        max(left[i - 1][1] + add[i - 1][1], left[i - 1][0] + add[i - 1][0] + timetable[i][0]),
                        # max(本batch的aug_start+t1,上一个batch的augstart+aug,
                        max(left[i - 1][2] + add[i - 1][2],
                            max(left[i - 1][1] + add[i - 1][1], left[i - 1][0] + add[i - 1][0] + timetable[i][0]) +
                            timetable[i][1])]

        left.append(cur_left)

    # add = [[14, 6, 8], [18, 7, 35], [10, 30, 21], [18, 5, 30], [10, 25, 20], [12, 35, 20], [10, 32, 17], [10, 20, 16]]
    # left = [[0, 14, 20], [14, 32, 43], [32, 42, 78], [42, 72, 99], [60, 77, 129], [70, 102, 149], [82, 137, 169],
    #         [92, 169, 189]]
    m = range(len(add))  # batch数量
    n = range(len(add[0]))
    color = ['b', 'g', 'r', 'y', 'c', 'm', 'k']

    # 画布设置,大小与分辨率

    # barh-柱状图换向,循坏迭代-层叠效果
    for i in m:
        for j in n:
            # plt.barh(y, width, left, edgecolor, color)
            plt.barh(m[i], add[i][j], left=left[i][j], color=color[j])
            plt.text(x=left[i][j] + add[i][j] / 2, y=m[i] - 0.2, s=str(add[i][j]), fontdict={'fontsize': 16})

    total_time = round(left[-1][-1] + add[-1][-1],ndigits=4)
    print(total_time)

    plt.title("  total_time=" + str(total_time), fontsize=25)
    labels = [''] * len(add[0])
    # 设置刻度字体大小
    plt.xticks(range(50), rotation=0, fontsize=20)
    plt.yticks(m, fontsize=20)
    labels = ['t0', 't1', 't2']
    # 图例绘制
    patches = [mpatches.Patch(color=color[i], label="{:s}".format(labels[i])) for i in range(len(add[0]))]
    plt.legend(handles=patches, loc=4, fontsize=25)
    plt.ylabel(" ", fontsize=30)
# XY轴标签
plt.xlabel("运行时间/s", fontsize=30)
plt.show()

绘制效果:

python绘制甘特图代码_第1张图片

 

你可能感兴趣的:(python实用,python,开发语言,后端)