如何在Plotly Gantt图中指定其他颜色?

时间:2019-05-03 08:04:56

标签: python-3.x plotly gantt-chart

我习惯于Plotly绘制甘特图:

fig = ff.create_gantt(df, index_col='Resource', show_colorbar=True, group_tasks=True)

索引何时输入

index_col='Resource'

超出 10 ,出现错误:

  

plotly.exceptions.PlotlyError:错误。 “颜色”中的颜色数量必须不少于组列中唯一索引值的数量。

我认为这是由于Plotly的默认颜色仅限于十种不同的颜色(例如Plotly colours list

我想要更多颜色(>= index of 'Resource')。如何添加和定义它们?

编辑: 这是一个可用于测试的示例

from __future__ import print_function

from collections import defaultdict

from plotly.offline import plot
import plotly.figure_factory as ff
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile

import datetime



def gantt_test():
    """Solve a small flexible jobshop problem."""

    # convert to date
    serial = 43466.0 # 01.01.2019 Excel
    seconds = (serial - 25569) * 86400.0 # convert to seconds
    date_date = datetime.datetime.utcfromtimestamp(seconds)
    date_string = date_date.strftime("%Y-%m-%d %H:%M:%S")

    df = [dict(Task="machine_99", Start=0, Finish=1, Resource="job_99")]
    df.clear()

    start_value = 0 # in min
    duration = 120  # in min

    for i in range(1, 12):              
        b_dict = dict(Task="M " + str(i), Start=datetime.datetime.utcfromtimestamp((serial - 25569 + (start_value/(60*24.0))) * 86400.0).strftime("%Y-%m-%d %H:%M:%S"), Finish=datetime.datetime.utcfromtimestamp((serial - 25569 + (start_value +duration)/(60*24.0)) * 86400.0).strftime("%Y-%m-%d %H:%M:%S"), Resource="job " + str(i))            
        df.append(b_dict)
        start_value = 10*i





    fig = ff.create_gantt(df, index_col='Resource', show_colorbar=True, group_tasks=True)

    plot(fig, filename='gantt-group-tasks-together.html')


gantt_test()


如果您更改

    for i in range(1, 12):   

小于

  

12

它起作用: enter image description here

2 个答案:

答案 0 :(得分:0)

我通过更改来使它工作

fig = ff.create_gantt(df, index_col='Resource', show_colorbar=True, group_tasks=True)

fig = ff.create_gantt(df, colors=colors, index_col='Resource', show_colorbar=True, group_tasks=True)

附加colors,如显示

    r = lambda: random.randint(0,255)
    #print('#%02X%02X%02X' % (r(),r(),r()))
    colors = ['#%02X%02X%02X' % (r(),r(),r())]

    for i in range(1, 15):              
        b_dict = dict(Task="M " + str(i), Start=datetime.datetime.utcfromtimestamp((serial - 25569 + (start_value/(60*24.0))) * 86400.0).strftime("%Y-%m-%d %H:%M:%S"), Finish=datetime.datetime.utcfromtimestamp((serial - 25569 + (start_value +duration)/(60*24.0)) * 86400.0).strftime("%Y-%m-%d %H:%M:%S"), Resource="job " + str(i))            
        df.append(b_dict)
        start_value = 10*i

        colors.append('#%02X%02X%02X' % (r(),r(),r()))

现在为每种资源添加了随机颜色。

答案 1 :(得分:0)

您还可以使用hashlib根据某些输入字符串(例如pandas Dataframe列)创建更多颜色。

一个最小的例子:

import hashlib

colours = []
for key in listOfStrings:
    colour = colFromStr(str(key))
    colours.append(f"#{colour}")
fig = plotly.figure_factory.create_gantt(dataToPlot, colors=colours)


def colFromStr(inputString):
    hashedString = hashlib.sha256(inputString.encode())
    return hashedString.hexdigest()[len(hashedString.hexdigest())-6:]