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

如何在Plotly Python共享X轴图表中添加实时垂直线?

解决Plotly共享X轴子图中当前时间垂直线显示错误的问题

问题根源

你代码中用datetime.datetime.now().timestamp()获取的是Unix时间戳(数值类型),但图表X轴使用的是pandas的datetime64类型日期数据,两者类型不匹配,导致Plotly无法正确映射到当前时间的位置,因此垂直线错误显示在遥远的过去。

修复方案

直接使用datetime对象或pandas的Timestamp对象作为add_vline的x参数,保持与X轴数据类型一致即可。

修改后的完整代码

import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
import datetime

# 示例数据
data1 = {
    'Date': pd.date_range(start='2023-09-01', periods=10, freq='D'),
    'Value1': [10, 12, 15, 8, 9, 11, 13, 14, 10, 12]
}

data2 = {
    'Date': pd.date_range(start='2023-09-01', periods=10, freq='D'),
    'Value2': [5, 7, 9, 6, 8, 10, 11, 12, 7, 6]
}

# 创建共享X轴的子图
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1)

# 添加第一个子图的折线
fig.add_trace(go.Scatter(x=data1['Date'], y=data1['Value1'], mode='lines', name='Value1'), row=1, col=1)

# 添加第二个子图的折线
fig.add_trace(go.Scatter(x=data2['Date'], y=data2['Value2'], mode='lines', name='Value2'), row=2, col=1)

# 获取当前时间的datetime对象(与X轴数据类型一致)
current_time = datetime.datetime.now()
# 也可以用pandas的Timestamp:current_time = pd.Timestamp.now()

# 在所有子图添加当前时间的红色虚线垂直线
fig.add_vline(x=current_time, line=dict(color='red', dash='dash'), annotation_text='Current Time', row='all')

# 显示图表
fig.show()

额外提示

如果当前时间不在现有数据的日期范围内,垂直线会显示在图表右侧(超出数据区间),可以通过以下代码调整X轴范围,让当前时间纳入显示区间:

fig.update_layout(xaxis_range=[data1['Date'].min(), current_time])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:13:30