使用时间戳绘制甘特图

问题描述 投票:0回答:1

我正在尝试使用 plotly 绘制甘特图。重要的是水平泳道可以有多个及时分开的条。

我找到了一个使用日历日期 (YYYY-MM-DD) 的示例,并尝试使用时间 (HH:MM:SS) 进行转换。但是当我使用时间戳时,一切都聚集在一起,没有间隙。

import plotly.express as px
import pandas as pd

df = pd.DataFrame([
    dict(Start='00:01:12', Finish='00:01:59', Resource="Alex"),
    dict(Start='00:04:51', Finish='00:05:28', Resource="Alex"),
    dict(Start='00:02:12', Finish='00:04:34', Resource="Max")
])

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

fig.update_layout(xaxis=dict(
                      title='Timestamp', 
                      tickformat = '%H:%M:%S',
                  ))
fig.show()

python timestamp plotly visualization gantt-chart
1个回答
4
投票

Plotly 甘特图仅适用于日期(请参阅这个问题),但一个可能的解决方法是将日期

1970-01-01
添加到所有时间的开头,然后显示时间而不在图中显示日期。

import plotly.express as px
import pandas as pd

df = pd.DataFrame([
    dict(Start='1970-01-01 00:01:12', Finish='1970-01-01 00:01:59', Resource="Alex"),
    dict(Start='1970-01-01 00:04:51', Finish='1970-01-01 00:05:28', Resource="Alex"),
    dict(Start='1970-01-01 00:02:12', Finish='1970-01-01 00:04:34', Resource="Max")
])

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

fig.update_layout(xaxis=dict(
                      title='Timestamp', 
                      tickformat = '%H:%M:%S',
                  ))
fig.show()

编辑:不幸的是,甘特图在不到 10 秒的时间间隔内中断,我不明白为什么。然而,我很确定在幕后,甘特图只不过是在图表上绘制的矩形,所以我们可以绘制这样一个小于 10 秒的间隔来实现类似的效果(除了没有悬停手工绘制的形状)

import plotly.express as px
import pandas as pd

df = pd.DataFrame([
    # dict(Start='1970-01-01 00:01:12', Finish='1970-01-01 00:01:19', Resource="Alex"),
    dict(Start='1970-01-01 00:04:51', Finish='1970-01-01 00:05:28', Resource="Alex"),
    dict(Start='1970-01-01 00:02:12', Finish='1970-01-01 00:04:34', Resource="Max")
])

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

# you can manually set the range as well
fig.update_layout(xaxis=dict(
                      title='Timestamp', 
                      tickformat = '%H:%M:%S',
                      range = ['1970-01-01 00:01:00','1970-01-01 00:06:00']
                  ))

# add a filled rectangle
fig.add_shape(
            type="rect",
            x0='1970-01-01 00:01:12',
            y0=0.6,
            x1='1970-01-01 00:01:19',
            y1=1.4,
            line=dict(color="rgb(98,115,241)"),
            fillcolor="rgb(98,115,241)",
        )

fig.show()

© www.soinside.com 2019 - 2024. All rights reserved.