You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将px.timeline与go.Table合并为同一子图并导出HTML文件

将Timeline图表与Table合并为同一子图并导出HTML

你可以通过plotly.subplots.make_subplots创建多子图布局,把Timeline和Table的图表对象整合到同一个画布中,具体实现代码如下:

from plotly.subplots import make_subplots
import pandas as pd
import plotly.express as px
import plotly.graph_objs as go

# 示例数据
df = pd.DataFrame({'Task': ['a1', 'a2', 'a3', 'a4', 'a5', 'a6'],
                   'Source': ['abc', 'completed', 'cancelled', 'deg', 'pki', 'API'],
                   'Start': ['2021-01-01', '2021-02-12', '2021-03-15', '2021-08-09', '2021-09-20', '2021-12-15'],
                   'Finish': ['2021-03-12', '2021-04-25', '2021-05-20', '2021-10-01', '2021-12-30', '2022-03-01']})

# 创建Timeline图表,指定y轴为Task让每个任务对应单独行
fig1 = px.timeline(df, x_start='Start', x_end='Finish', y='Task')

# 定义Table的trace对象
table_trace = go.Table(
    header=dict(
        values=['Task', 'Source', 'Start', 'Finish'],
        line_color='white', 
        fill_color='white',
        align='center'
    ),
    cells=dict(
        values=[df['Task'], df['Source'], df['Start'], df['Finish']],
        align='center'
    )
)

# 创建2行1列的子图布局,指定各子图类型
fig = make_subplots(
    rows=2, cols=1,
    subplot_titles=('任务时间线', '任务详情表'),
    row_heights=[0.7, 0.3],  # 分配两行高度比例
    specs=[[{"type": "scatter"}], [{"type": "table"}]]
)

# 将Timeline的所有trace添加到第一行子图
for trace in fig1.data:
    fig.add_trace(trace, row=1, col=1)

# 将Table的trace添加到第二行子图
fig.add_trace(table_trace, row=2, col=1)

# 调整整体布局样式
fig.update_layout(
    height=700,
    title_text='任务时间线与详情表',
    showlegend=False  # 关闭Timeline默认图例
)

# 导出为可直接打开的HTML文件
fig.write_html('task_timeline_table.html')

关键说明:

  • 用make_subplots定义布局时,通过specs参数指定子图类型,确保Table能正常渲染。
  • px.timeline生成的是散点类trace,需要遍历fig1.data将所有元素添加到子图中。
  • 通过row_heights调整两行高度占比,让时间线和表格都有合适的显示空间。
  • 执行代码后会在当前目录生成task_timeline_table.html文件,直接打开即可查看整合后的可视化效果。

内容的提问来源于stack exchange,提问作者XaviorL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 23:33:25