【问题标题】:How to specify color for elements in plotly Gannt chart?如何为绘图甘特图中的元素指定颜色?
【发布时间】:2020-12-12 23:31:55
【问题描述】:

我在这里学习 python 教程:https://plotly.com/python/gantt/

import pandas as pd
import plotly.express as px
df = pd.DataFrame([
    dict(Task="Job A", Start='2009-01-01', Finish='2009-02-25'),
    dict(Task="Job A", Start='2009-02-26', Finish='2009-03-28'),
    dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15'),
    dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30')
])

print(df)

    Task       Start      Finish
0  Job A  2009-01-01  2009-02-25
1  Job A  2009-02-26  2009-03-28
2  Job B  2009-03-05  2009-04-15
3  Job C  2009-02-20  2009-05-30

上面教程中的代码给了我图表:

fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task")
fig.update_yaxes(autorange="reversed") # otherwise tasks are listed from the bottom up
fig.show()

请注意,Job A 有两个事件。

我想为每个开始和结束交替使用颜色。例如第一个事件红色,第二个事件蓝色,第三个事件红色,第四个事件蓝色等。

我尝试了color_discrete_sequencecolor_discrete_map 参数,但颜色不交替。

我尝试过的:

fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task",color_discrete_sequence=["red", "blue"])
fig.update_yaxes(autorange="reversed") 
fig.show()

fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task",color_discrete_map={"Start": "red","Finish":'blue'})
fig.update_yaxes(autorange="reversed") 
fig.show()

关于如何交替颜色的任何想法?

我希望工作 A 的外观示例:

【问题讨论】:

    标签: python plotly plotly-python


    【解决方案1】:

    只需添加一个描述所需颜色的列。

    import pandas as pd
    import plotly.express as px
    df = pd.DataFrame([
        dict(Task="Job A", Start='2009-01-01', Finish='2009-02-25', Color='blue'),
        dict(Task="Job A", Start='2009-02-26', Finish='2009-03-28', Color='red'),
        dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15', Color='blue'),
        dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30', Color='blue')
    ])
    
    fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task", color="Color")
    fig.update_yaxes(autorange="reversed") # otherwise tasks are listed from the bottom up
    fig.show()
    

    【讨论】:

    • 谢谢。这适用于上面的小型测试数据框。但是有没有更自动化的方法?我的实际数据框中有几千列。有许多任务以及开始和结束日期。
    • 如果您的问题是关于颜色的,那么您不必明确指定颜色。例如,您可以使用具有值 {"Alice"、"Bob、"Carol"} 的列“Worker”,甘特图将相应着色。如果是关于如何在组内交错值:使用groupby,创建一个带有计数器的列并取一个计数器的余数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 2016-05-11
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多