首页 > 解决方案 > 如何更新绘图并保留 UI 设置?

问题描述

以下代码创建两个子图并在浏览器窗口中每秒更新一次。

我可以缩放它并隐藏绘图中的一些线条,但每秒所有数据都会更新并将缩放和所有线条可见性设置为默认值

如何在更新时保留缩放和选定线的设置?

import datetime
import random

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from plotly.subplots import make_subplots

# https://dash.plotly.com/live-updates

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div(
    html.Div([
        html.H4('Two random plots'),
        dcc.Graph(id='live-update-graph'),
        dcc.Interval(
            id='interval-component',
            interval=1 * 1000,  # in milliseconds
            n_intervals=0
        )
    ])
)

DATA = {
    'time': [],
    'val0': [],
    'val1_1': [],
    'val1_2': []
}


def update_data():
    DATA['val0'].append(random.randint(0, 50))
    DATA['val1_1'].append(random.randint(0, 50))
    DATA['val1_2'].append(random.randint(0, 50))
    DATA['time'].append(datetime.datetime.now())


@app.callback(Output('live-update-graph', 'figure'),
              Input('interval-component', 'n_intervals'))
def update_graph_live(n):
    update_data()

    # Create the graph with subplots
    fig = make_subplots(rows=2, cols=1, vertical_spacing=0.2)
    fig['layout']['margin'] = {'l': 30, 'r': 10, 'b': 30, 't': 10}
    fig['layout']['legend'] = {'x': 0, 'y': 1, 'xanchor': 'left'}

    fig.append_trace({
        'x': DATA['time'],
        'y': DATA['val0'],
        'name': 'val 0',
        'mode': 'lines+markers',
        'type': 'scatter'
    }, 1, 1)

    fig.append_trace({
        'x': DATA['time'],
        'y': DATA['val1_1'],
        'text': DATA['time'],
        'name': 'val 1.1',
        'mode': 'lines+markers',
        'type': 'scatter'
    }, 2, 1)

    fig.append_trace({
        'x': DATA['time'],
        'y': DATA['val1_2'],
        'text': DATA['time'],
        'name': 'val 1.2',
        'mode': 'lines+markers',
        'type': 'scatter'
    }, 2, 1)

    return fig


if __name__ == '__main__':
    app.run_server(debug=True)

标签: pythonplotplotlydata-visualizationplotly-dash

解决方案


自 2018 年 11 月以来,Plotly 社区论坛上发布了一个解决方案。的layout财产的figure财产dcc.Graph有一个财产uirevision,帖子说:

uirevision是魔法发生的地方。此键由 内部跟踪dcc.Graph,当它从一个更新更改为下一个更新时,它会重置所有用户驱动的交互(如缩放、平移、单击图例项)。如果它保持不变,那么用户驱动的 UI 状态就不会改变。

因此,如果您不想重置缩放设置,无论底层数据发生多少变化,只需设置uirevision为常量,如下所示:

fig['layout']['uirevision'] = 'some-constant'

在更新函数中返回图形之前。

还有更多

在某些情况下,您需要更多控制权。假设绘图的 x 和 y 数据可以单独更改。也许 x 总是时间,但 y 可以在价格和数量之间变化。您可能希望在重置 y 缩放时保留 x 缩放。有很多uirevision属性,通常都继承自,layout.uirevision但如果需要,您可以单独设置它们。在这种情况下,设置一个常数xaxis.uirevision = 'time',但让和yaxis.revision之间变化。确保仍然设置以保留其他项目,例如跟踪可见性和模式栏按钮!'price''volume'layout.uirevision


推荐阅读