如何让 plotly.express.timeline 重叠条可见

How to get plotly.express.timeline overlapped bars to be visible

我想知道是否有人有解决时间轴条重叠的方法?

import plotly.express as px
import pandas as pd

df = pd.DataFrame([
    dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Resource="Alex"),
    dict(Task="Job B", Start='2009-02-25', Finish='2009-04-15', Resource="Alex"),
    dict(Task="Job C", Start='2009-02-23', Finish='2009-05-23', Resource="Max"),
    dict(Task="Job D", Start='2009-02-20', Finish='2009-05-30', Resource="Max")
])

fig = px.timeline(df, x_start="Start", x_end="Finish", y="Resource", color="Resource")
fig.show()

而且在图像中很难看到:

有什么建议吗?

我能想到的最好的方法是对所有 "Tasks""Jobs" 使用不同的颜色,并且必须 opacity 较低以便可以看到traces/bars 被覆盖

代码如下:

import plotly.express as px
import pandas as pd

df = pd.DataFrame([
    dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Resource="Alex"),
    dict(Task="Job B", Start='2009-02-25', Finish='2009-04-15', Resource="Alex"),
    dict(Task="Job C", Start='2009-02-23', Finish='2009-05-23', Resource="Max"),
    dict(Task="Job D", Start='2009-02-20', Finish='2009-05-30', Resource="Max")
])

fig = px.timeline(df, x_start="Start", x_end="Finish", y="Resource", color="Task", opacity=0.5)

fig.show()

图表如下所示:

我经常发现为某些类别分配不同的 width 有助于使整个内容更易于阅读。因此,在您的情况下,我会在指定的 df 中包含一列,然后使用以下内容编辑图形:

for i, d in enumerate(fig.data):
    d.width = df[df['Task']==d.name]['width']

剧情:

带有已编辑数据的完整代码:

import plotly.express as px
import pandas as pd

resource = ['Alex', 'Max']
df = pd.DataFrame([
    dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Resource="Alex", width = 0.5),
    dict(Task="Job B", Start='2009-02-25', Finish='2009-04-15', Resource="Alex", width = 0.2),
    dict(Task="Job C", Start='2009-02-23', Finish='2009-05-23', Resource="Max", width = 0.5),
    dict(Task="Job D", Start='2009-02-20', Finish='2009-05-30', Resource="Max", width = 0.2)
])

fig = px.timeline(df, x_start="Start", x_end="Finish", y="Resource", color="Task")

for i, d in enumerate(fig.data):
    d.width = df[df['Task']==d.name]['width']
fig.show()