我最终尝试将 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()
您还需要添加对象的布局
px.timeline
。然后它应该按预期呈现:对于未来的读者,我找到了另一种解决方案。只需在 .show() 之前添加这一行即可。
Fig_bad.update_xaxes(type='date')