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

将Plotly px.timeline嵌入子图后格式异常的修复方法咨询

修复Plotly Express Timeline嵌入Subplots的显示异常问题

问题根源

Plotly Express生成的px.timeline默认使用category类型y轴,并自动处理分类标签的映射关系。但直接将其trace添加到subplots时,子图默认的y轴配置(如类型、刻度映射)与原timeline不匹配,导致显示错位、格式异常。

修复步骤及代码示例

1. 异常代码示例(复现问题)

import plotly.express as px
import plotly.subplots as sp

# 构造测试数据
df = px.data.tips()
df['start'] = df['time'].map({'Lunch': 1, 'Dinner': 2})
df['end'] = df['start'] + 1

# 单独显示正常的timeline图表
fig1 = px.timeline(df, x_start='start', x_end='end', y='day', color='sex')
fig1.show()

# 直接嵌入子图后显示异常
fig_sub = sp.make_subplots(rows=1, cols=2)
for trace in fig1.data:
    fig_sub.add_trace(trace, row=1, col=1)
fig_sub.show()

2. 修复后的代码

import plotly.express as px
import plotly.subplots as sp

# 构造测试数据
df = px.data.tips()
df['start'] = df['time'].map({'Lunch': 1, 'Dinner': 2})
df['end'] = df['start'] + 1

# 生成原始timeline图表
fig1 = px.timeline(df, x_start='start', x_end='end', y='day', color='sex')

# 创建子图时预留匹配的轴配置
fig_sub = sp.make_subplots(rows=1, cols=2, specs=[[{'type': 'xy'}, {'type': 'xy'}]])

# 添加所有timeline trace到子图
for trace in fig1.data:
    fig_sub.add_trace(trace, row=1, col=1)

# 同步原timeline的y轴核心配置到子图
fig_sub.update_yaxes(
    type='category',  # 强制设置为分类轴,与px.timeline默认一致
    categoryorder='total ascending',  # 同步分类排序规则
    ticktext=fig1.layout.yaxis.ticktext,  # 同步刻度显示文本
    tickvals=fig1.layout.yaxis.tickvals,  # 同步刻度映射值
    title=fig1.layout.yaxis.title,  # 同步轴标题
    row=1, col=1
)

# 同步x轴配置(可选)
fig_sub.update_xaxes(
    title=fig1.layout.xaxis.title,
    row=1, col=1
)

# 同步图例配置(subplots不会自动继承原图例)
fig_sub.update_layout(
    legend=fig1.layout.legend,
    title='Timeline in Subplots'
)

fig_sub.show()

核心修复要点

  • 强制子图y轴类型为category:与px.timeline的默认轴类型保持一致
  • 同步刻度映射关系:复制原timeline的ticktext和tickvals,确保分类标签与条形位置匹配
  • 完整添加所有trace:px.timeline会根据color参数生成多个trace,需全部添加到子图
  • 手动同步布局元素:子图不会自动继承原图表的图例、轴标题等配置,需手动同步

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 17:05:14