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

Plotly Express Timeline双X轴优化:UTC与固定Epoch时间差展示

解决方案:无虚拟轨迹+实时同步双X轴实现

核心改进

  • 移除冗余的虚拟go.Scatter轨迹,直接在px.timeline生成的图表上添加顶部X轴
  • 利用Plotly的自定义刻度格式化函数,实现主X轴(UTC时间)与顶部X轴(epoch差值)的实时联动
  • 彻底解决缩放/拖拽时双轴错位问题,代码更简洁

完整代码

import pandas as pd
import plotly.express as px
import datetime as dt

# 示例活动数据
df = pd.DataFrame([
    dict(task="A", start='2023-01-01 01:00:00', end='2023-01-01 02:00:00'),
    dict(task="B", start='2023-01-01 02:00:00', end='2023-01-01 03:00:00'),
    dict(task="C", start='2023-01-01 03:00:00', end='2023-01-01 04:00:00'),
    dict(task="D", start='2023-01-01 04:00:00', end='2023-01-01 05:00:00'),
])

# 定义固定epoch时间
fmt = "%Y-%m-%d %H:%M:%S"
fixed_epoch = dt.datetime.strptime("2023-01-01 02:33:00", fmt)
# 转换为毫秒级时间戳(Plotly内部处理时间的默认单位)
epoch_ts_ms = fixed_epoch.timestamp() * 1000

# 生成基础时间线图表
timeline = px.timeline(df, x_start="start", x_end="end", y="task")
# 添加epoch标记竖线
timeline.add_vline(x=fixed_epoch, line_width=2.5, line_color="red")

# 配置双X轴:主轴UTC时间,顶部轴显示与epoch的秒数差
timeline.update_layout(
    title_text='ACTIVITY TIMELINE',
    xaxis=dict(
        title='UTC',
        # 可选:设置初始显示范围,不设置则自动适配数据
        range=[
            dt.datetime.strptime(min(df["start"]), fmt) - dt.timedelta(hours=0.5),
            dt.datetime.strptime(max(df["end"]), fmt) + dt.timedelta(hours=0.5)
        ]
    ),
    xaxis2=dict(
        title='Time from epoch (sec)',
        side='top',
        overlaying='x',
        type='linear',
        # 自定义刻度格式化函数:将毫秒时间戳转换为与epoch的秒数差
        tickformatfunction=f"""function(d) {{
            const epoch_ms = {epoch_ts_ms};
            return ((d - epoch_ms)/1000).toFixed(1);
        }}""",
        autorange=True
    )
)

timeline.show()

方案优势

  1. 无错位问题:自定义格式化函数会实时根据主X轴的刻度值计算顶部轴的显示内容,缩放、拖拽操作时双轴完全同步
  2. 代码简洁:无需使用make_subplots和虚拟轨迹,直接基于原始timeline图表扩展
  3. 灵活性高:可以通过修改toFixed(1)调整秒数的精度,或修改函数逻辑实现其他时间差单位(如分钟、小时)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 05:48:12