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

如何在Python Dash/Plotly实时图表中高亮x0-x1区域?

在无显式fig对象的Dash实时图表中添加时间区域高亮(vrect)

完全可以实现,核心是直接操作图表的layout.shapes属性,不需要显式创建fig对象,以下是具体实现步骤:

  • 初始化图表时预留shapes位置
    在dcc.Graph的初始配置中,给layout设置空的shapes数组,用于后续动态添加高亮区域:

    dcc.Graph(
        id='live-graph',
        figure={
            'data': [{'x': [], 'y': [], 'type': 'line', 'name': '实时数据'}],
            'layout': {
                'title': '实时数据图表',
                'shapes': []
            }
        }
    )
    
  • 回调中同步更新数据与高亮区域
    在更新实时数据的回调里,通过State获取当前图表的配置对象,直接修改其layout.shapes来添加vrect:

    import datetime
    import random
    from dash import Dash, dcc, html, Input, Output, State
    
    app = Dash(__name__)
    
    app.layout = html.Div([
        dcc.Graph(id='live-graph'),
        dcc.Interval(id='interval-component', interval=1000, n_intervals=0)
    ])
    
    @app.callback(
        Output('live-graph', 'figure'),
        Input('interval-component', 'n_intervals'),
        State('live-graph', 'figure')
    )
    def update_graph(n, current_fig):
        # 追加新的实时数据
        new_x = datetime.datetime.now()
        new_y = random.random()
        current_fig['data'][0]['x'].append(new_x)
        current_fig['data'][0]['y'].append(new_y)
    
        # 定义要高亮的时间区间(示例:最近10秒)
        highlight_start = new_x - datetime.timedelta(seconds=10)
        # 更新shapes,替换为新的高亮区域
        current_fig['layout']['shapes'] = [
            {
                'type': 'rect',
                'x0': highlight_start,
                'x1': new_x,
                'y0': 0,
                'y1': 1,
                'xref': 'x',  # 绑定到x轴
                'yref': 'paper',  # 覆盖整个y轴高度
                'fillcolor': 'rgba(0,255,0,0.15)',  # 半透明绿色
                'line': {'width': 0}  # 隐藏边框
            }
        ]
    
        # 限制历史数据量,避免性能问题
        if len(current_fig['data'][0]['x']) > 100:
            current_fig['data'][0]['x'] = current_fig['data'][0]['x'][-100:]
            current_fig['data'][0]['y'] = current_fig['data'][0]['y'][-100:]
    
        return current_fig
    
    if __name__ == '__main__':
        app.run_server(debug=True)
    
  • 关键注意事项

    • 确保x0和x1的时间格式与图表x轴数据格式一致(比如用datetime对象或ISO标准字符串)
    • 若需要多个高亮区域,只需在shapes数组中添加多个rect配置即可
    • 每次回调可以选择替换整个shapes数组(避免旧高亮残留),或追加新的区域

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 18:58:13