plotly - 使用 add_trace() 添加时间轴到 go.Figure 对象

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

我最终尝试将 px.timeline 添加到包含 go.Scatter 的图中(类似于他们在这里所做的事情:将 Plotly Express 跟踪添加到具有多个跟踪的图形对象 go.Figure()?) .

执行此操作时,时间线不会显示。当我使用 add_trace() 函数时,我已将其范围缩小到一个问题。如果我在创建Figure对象时直接使用px.timeline,我的时间线显示得很好,但是当我尝试使用Figure.add_trace()将其添加到现有的Figure时,它看起来很奇怪。 x 轴不再显示时间。

显示此行为的独立代码片段如下所示。非常感谢任何帮助!

import pandas as pd
import plotly.graph_objects as go
import plotly.express as px

mydata_as_json = '{"Start_Time":{"0":"2023-11-01 16:48:24.8","1":"2023-11-01 16:49:47.7","2":"2023-11-01 16:53:23.3","3":"2023-11-01 16:56:08.6","4":"2023-11-01 16:58:37.9","5":"2023-11-01 17:00:10.9"},"End_Time":{"0":"2023-11-01 16:48:37.7","1":"2023-11-01 16:51:44.3","2":"2023-11-01 16:54:00.2","3":"2023-11-01 16:57:23.4","4":"2023-11-01 16:58:56.8","5":"2023-11-01 17:01:59.1"},"Instr":{"0":"MVIC","1":"LEISA","2":"MVIC","3":"LEISA","4":"MVIC","5":"LEISA"}}'

df = pd.DataFrame(eval(mydata_as_json))

# This works
fig_good = px.timeline(
    df, 
    x_start="Start_Time", 
    x_end="End_Time", 
    y="Instr", 
)
fig_good.show()

# This doesn't work. Why?
fig_bad = go.Figure()
fig_bad = fig_bad.add_trace(
        px.timeline(
            df, 
            x_start='Start_Time', 
            x_end='End_Time', 
            y='Instr',
        ).data[0]
)
fig_bad.show()

plotly gantt-chart plotly-express plotly.graph-objects
1个回答
0
投票

您还需要从

px.timeline
对象添加布局。然后它应该按预期呈现:

fig_bad = go.Figure()
px_timeline = px.timeline(
            df, 
            x_start='Start_Time', 
            x_end='End_Time', 
            y='Instr',
        )
fig_bad = fig_bad.add_trace(
        px_timeline.data[0]
)
fig_bad.layout = px_timeline.layout
fig_bad.show()

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