我在这里关注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_sequence
和color_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看起来像一个例子:
答案 0 :(得分:0)
只需添加描述所需颜色的列即可。
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()