在 dcc.Graph 中使用 extendData 的正确方法是什么?

What is the correct way of using extendData in dcc.Graph?

我正在尝试使用以下代码限制 dcc.Graph 图形绘制的点数:

import dash
import dash_html_components as html
import dash_core_components as dcc
import numpy as np

from dash.dependencies import Input, Output, State

# Example data (a circle).
resolution = 1000
t = np.linspace(0, np.pi * 2, resolution)
x, y = np.cos(t), np.sin(t)
# Example app.
figure = dict(data=[{'x': [], 'y': []}])
app = dash.Dash(__name__, update_title=None)  # remove "Updating..." from title
app.layout = html.Div([
    dcc.Graph(id='graph', figure=dict(figure)), dcc.Interval(id="interval", interval=10),
    dcc.Store(id='store', data=dict(x=x, y=y, resolution=resolution)),
])
app.clientside_callback(
    """
    function (n_intervals, data) {
        return [{x: [data.x], y: [data.y]}, [0], 10]
    }
    """,
    [Output('graph', 'extendData')],
    [Input('interval', 'n_intervals')], 
    [State('store', 'data')]
)

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

我所期望的是,当我使用 return [{x: [data.x], y: [data.y]}, [0], 10] 时,最后的 10 将图表上的点数限制为 10。虽然,当我 运行 示例代码时,一个绘制完整的圆圈。根据文档,extendData 需要以下 return:

extendData (list | dict; optional): Data that should be appended to existing traces. Has the form [updateData, traceIndices, maxPoints], where updateData is an object containing the data to extend, traceIndices (optional) is an array of trace indices that should be extended, and maxPoints (optional) is either an integer defining the maximum number of points allowed or an object with key:value pairs matching updateData Reference the Plotly.extendTraces API for full usage: https://plotly.com/javascript/plotlyjs-function-reference/#plotlyextendtraces

是我误解了 maxPoints 参数的使用,还是我实施错误?

你的错误很微妙,我花了一段时间才弄明白...

在你的回调装饰器中:

app.clientside_callback(
    """
    function (n_intervals, data) {
        return [{x: [data.x], y: [data.y]}, [0], 10]
    }
    """,
    [Output('graph', 'extendData')],
    [Input('interval', 'n_intervals')], 
    [State('store', 'data')]
)

由于 Output 在列表中,您的 return 也应该是一个以 extendData 作为单个元素的列表。但是,您 return 正在“解压” extendedData,因此 Dash 会忽略其他两个元素并仅发送 updateData={x: [data.x], y: [data.y]}.

要修复它,只需使用不在列表中的 Output('graph', 'extendData')