如何在单个柱中绘制时间线?

How to plot timeline in a single bar?

我正在尝试绘制时间线图表,但它们相互叠加。

import pandas as pd
import plotly.express as pex

d1 = dict(Start= '2021-10-10 02:00:00', Finish = '2021-10-10 09:00:00', Task = 'Sleep')
d2 = dict(Start= '2021-10-10 09:00:00', Finish = '2021-10-10 09:30:00', Task = 'EAT')
d3 = dict(Start= '2021-10-10 09:30:00', Finish = '2021-10-10 12:00:00', Task = 'Study')
d4 = dict(Start= '2021-10-10 12:00:00', Finish = '2021-10-10 16:00:00', Task = 'Work')
d5 = dict(Start= '2021-10-10 16:00:00', Finish = '2021-10-10 16:50:00', Task = 'EAT')
d6 = dict(Start= '2021-10-10 17:00:00', Finish = '2021-10-10 20:00:00', Task = 'Study')
d8 = dict(Start= '2021-10-10 20:00:00', Finish = '2021-10-10 20:40:00', Task = 'EAT')
d7 = dict(Start= '2021-10-10 21:00:00', Finish = '2021-10-11 05:00:00', Task = 'Sleep')

df = pd.DataFrame([d1,d2,d3,d4,d5,d6,d7,d8])

我的 DataFrame(df) 是:

gantt = pex.timeline(df, x_start='Start', x_end = 'Finish', color = 'Task', height=300)
gantt.show()

这是我得到的图表。但我不希望它们堆叠。我希望它们在一行中(不会有任何重叠的间隔)。我该如何实现?

试试这个

import pandas as pd
import plotly.express as pex

d1 = dict(stack=1, start='2021-10-10 02:00:00', finish='2021-10-10 09:00:00', task='Sleep')
d2 = dict(stack=1, start='2021-10-10 09:00:00', finish='2021-10-10 09:30:00', task='EAT')
d3 = dict(stack=1, start='2021-10-10 09:30:00', finish='2021-10-10 12:00:00', task='Study')
d4 = dict(stack=1, start='2021-10-10 12:00:00', finish='2021-10-10 16:00:00', task='Work')
d5 = dict(stack=1, start='2021-10-10 16:00:00', finish='2021-10-10 16:50:00', task='EAT')
d6 = dict(stack=1, start='2021-10-10 17:00:00', finish='2021-10-10 20:00:00', task='Study')
d8 = dict(stack=1, start='2021-10-10 20:00:00', finish='2021-10-10 20:40:00', task='EAT')
d7 = dict(stack=1, start='2021-10-10 21:00:00', finish='2021-10-11 05:00:00', task='Sleep')

df = pd.DataFrame([d1,d2,d3,d4,d5,d6,d7,d8])

gantt = pex.timeline(df, x_start='start', x_end='finish', y='stack', color='task', height=300)
gantt

根据documentation,您可以使用y参数并提供大小等于df中行数和所有元素的array_like对象等于。

因此,一种方法(使用空字符串 '' 导致绘图没有 y-axis 范围):

gantt = pex.timeline(df, x_start='Start', x_end = 'Finish', color = 'Task', height=300, y=['']*df.shape[0])