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

Plotly中rangemode='tozero'对datetime格式无效,如何设置X轴从00:00:00开始?

让Plotly时间线图表X轴从00:00:00开始的解决方法

问题描述

我使用Plotly绘制时间线图表时,希望X轴从00:00:00开始,在xaxis配置中设置rangemode='tozero'后并未生效,请问正确的实现方法是什么?

我的实现代码

import plotly.express as px
import pandas as pd
import io
import numpy as np
import datetime

def save_fig(fig,width,height,pngname):
    fig.write_image(pngname,format="png", width=width, height=height, scale=1)
    print("[[%s]]"%pngname)
    #fig.show()
    return

def main():
    title = "bootchart startup time"
    xlabel = "Timestamp"
    ylabel = "Train"
    width = 800
    height = 400
    
    pngname = "/media/sf_work/demo.png"

    data = '''
name,start,end
A,5,10
B,7,10
C,4,10
'''

    df = pd.read_csv(io.StringIO(data))
    for name in ['start','end']:
        df[name] = pd.to_datetime(df[name], unit='s')

    fig = px.timeline(df, x_start="start", x_end="end", y="name", color="name")
    layout = dict(
        title=title,
        xaxis_title=xlabel,
        yaxis_title=ylabel,
        title_x=0.5,   
        margin=dict(l=10,t=20,r=0,b=40),
        width=width,
        height=height,
        plot_bgcolor='#ffffff',
        paper_bgcolor='#ffffff',        
        hoverlabel=dict(
            bgcolor="white",
            font_size=8,
            font_family="Rockwell"
        ),
        showlegend=False,
        xaxis=dict(
            rangemode="tozero",
            tickmode='array',
            tickangle=-25,
            tickformat='%H:%M:%S',
            showline=True,
            linecolor='black',
            linewidth=.5,
            ticks='outside',
            zeroline=True,
        ),
        yaxis=dict(
            side='right',
            showline=False,
            linecolor='black',
            linewidth=.5,            
            showgrid=False,
            gridcolor='grey',
            gridwidth=.5,
        ),        
    )
    fig.update_layout(layout)
    save_fig(fig,width,height,pngname)
    return

main()

当前图表效果

当前图表

解决方案

rangemode='tozero'不生效的原因是:你的时间数据由Unix时间戳(单位秒)转换而来,默认0秒对应的是1970-01-01 00:00:00 UTC,但Plotly的rangemode='tozero'会尝试匹配原始时间轴的零点,而非你期望的相对时间零点。要实现X轴从00:00:00开始,需要手动指定X轴的起始范围:

  1. 先定义0秒对应的datetime对象:
zero_time = pd.to_datetime(0, unit='s')
  1. 在xaxis配置中移除rangemode="tozero",替换为range=[zero_time, df['end'].max()],强制X轴从0秒对应的时间点开始。

修改后的关键代码片段

def main():
    # ... 其他代码不变 ...

    df = pd.read_csv(io.StringIO(data))
    for name in ['start','end']:
        df[name] = pd.to_datetime(df[name], unit='s')
    # 新增:定义0秒对应的时间点
    zero_time = pd.to_datetime(0, unit='s')

    fig = px.timeline(df, x_start="start", x_end="end", y="name", color="name")
    layout = dict(
        # ... 其他布局配置不变 ...
        xaxis=dict(
            # 手动设置X轴范围,替换rangemode参数
            range=[zero_time, df['end'].max()],
            tickmode='array',
            tickangle=-25,
            tickformat='%H:%M:%S',
            showline=True,
            linecolor='black',
            linewidth=.5,
            ticks='outside',
            zeroline=True,
        ),
        # ... 其他轴配置不变 ...
    )
    fig.update_layout(layout)
    save_fig(fig,width,height,pngname)
    return

这样修改后,X轴会从00:00:00开始显示,符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 00:00:55