如何用Plotly Graph Objects实现带正确时间轴的水平条形时间线图
解决方案:纯Plotly Graph Objects实现水平时间线图
你的代码存在两个核心问题:一是时间以字符串传入,Plotly无法识别为时间序列;二是误用了x参数(水平条形图中x代表条形长度,而非时间点/范围)。以下是纯Graph Objects的修正方案:
关键修正点
- 将字符串时间转换为
datetime对象,让Plotly正确解析时间数据 - 使用
x0和x1参数定义时间范围(时间点可设为相同值),替代原代码的x参数 - 强制X轴为时间类型,并配置显示格式
完整代码
import plotly.graph_objects as go from datetime import datetime # 定义时间格式并转换字符串时间为datetime对象 time_pattern = "%y-%m-%d %H:%M:%S" event_times = [ datetime.strptime("22-07-01 00:00:08", time_pattern), datetime.strptime("22-07-01 00:00:18", time_pattern), datetime.strptime("22-07-01 00:00:05", time_pattern) ] fig = go.Figure() # 添加时间点类型的条形(x0=x1表示单个时间点) fig.add_trace(go.Bar( y=['AndOn'], x0=event_times[0], x1=event_times[0], name='SF Zoo', orientation='h', legendgroup="group1", marker=dict( color='rgba(246, 78, 139, 0.6)', line=dict(color='rgba(246, 78, 139, 1.0)', width=1) ), width=0.1 # 调整条形宽度,适配时间点显示 )) fig.add_trace(go.Bar( y=['AndOn'], x0=event_times[1], x1=event_times[1], name='LA Zoo', legendgroup="group2", orientation='h', marker=dict( color='rgba(58, 71, 80, 0.6)', line=dict(color='rgba(58, 71, 80, 1.0)', width=1) ), width=0.1 )) fig.add_trace(go.Bar( y=['AndOn'], x0=event_times[2], x1=event_times[2], name='SF Zoo', legendgroup="group1", orientation='h', marker=dict( color='rgba(246, 78, 139, 0.6)', line=dict(color='rgba(246, 78, 139, 1.0)', width=1) ), width=0.1 )) # 配置时间轴显示 fig.update_xaxes( type='datetime', tickformat='%y-%m-%d %H:%M:%S', title_text='时间' ) # 调整布局避免重叠 fig.update_layout( barmode='group', title='水平时间线图', yaxis_title='类别' ) fig.show()
扩展:展示时间段
如果需要展示事件的持续时间,只需将x0设为起始时间,x1设为结束时间即可,示例:
# 示例:添加一个持续时间段的条形 fig.add_trace(go.Bar( y=['AndOn'], x0=event_times[2], # 开始时间:00:00:05 x1=event_times[0], # 结束时间:00:00:08 name='SF Zoo 持续事件', legendgroup="group1", orientation='h', marker=dict( color='rgba(246, 78, 139, 0.6)', line=dict(color='rgba(246, 78, 139, 1.0)', width=1) ) ))
内容的提问来源于stack exchange,提问作者sovon
相关产品推荐
相关产品推荐

