破折号巧妙地克服了重复的回调

Posted

技术标签:

【中文标题】破折号巧妙地克服了重复的回调【英文标题】:Dash plotly overcoming duplicate callback 【发布时间】:2021-05-21 22:28:03 【问题描述】:

我有一个仪表板,用于在预测值旁边显示历史数据。我希望用户能够对预测值进行编辑并更新图表。我通过一个可编辑的数据表来实现这一点。但是,我不确定在可编辑数据表上获取用户输入后如何更新散点图。

示例数据框

item   time_period  number  forecast
apple   1            5         0
apple   2            10        0
apple   3            8         0
apple   4            9         1
apple   5            12        1
orange  1            20        0
orange  2            46        0
orange  3            35        0
orange  4            32        1
orange  5            55        1

当前代码

import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd
import dash_table
from dash.dependencies import Input, Output



external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

raw_data = "item": ["apple", "apple", "apple", "apple", "apple", "orange", "orange", "orange", "orange", "orange"], "time_period":[1,2,3,4,5,1,2,3,4,5], "number":[5, 10, 8, 9, 12, 20, 46, 35, 32, 55],
            "forecast": [0,0,0,1,1,0,0,0,1,1]
df = pd.DataFrame(raw_data)
items = df["item"].unique()

app.layout = html.Div([
    dcc.Graph(
        id="scatter-plot"
    ),
    dcc.Dropdown(
        id="dropdown",
        options=["label":i, "value":i for i in items]
    ),
    dash_table.DataTable(
        id="data-table",
        columns=["id": "time_period", "name":"time_period", "id":"number", "name":"number", "editable":True],
        data=df.to_dict("records")
    )
])

@app.callback(
    Output(component_id="scatter-plot", component_property="figure"),
    Output(component_id="data-table", component_property="data"),
    Input(component_id="dropdown", component_property="value")
)

def select_item(fruit):

    # create copy of original dataframe
    dff = df.copy()

    # isolate out fruit from dropdown
    fruit_df = dff[dff["item"] == fruit]

    # create scatter plot for selected brand
    fig = px.scatter(data_frame=fruit_df, x="time_period", y="number", color="forecast")

    # isolate ordered cases and item
    forecasts = fruit_df[["time_period", "number"]]
    forecasts = forecasts.to_dict("records")

    return fig, forecasts

@app.callback(
    Output(component_id="scatter-plot", component_property="figure"),
    Input(component_id="data-table", component_property="data")
)

def update_scatter(data):
    fig = px.scatter(data_frame=data, x="time_period", y="number")
    return fig

app.run_server(debug=True)

【问题讨论】:

【参考方案1】:

将两者结合起来,并使用callback context 来确定是哪个输入导致回调触发。

【讨论】:

以上是关于破折号巧妙地克服了重复的回调的主要内容,如果未能解决你的问题,请参考以下文章

使用 Graphql-js 模式克服代码重复

如何优雅地克服无意义的 C++ 编译器警告?

克服 n^2 运行时程序

如何克服心煩氣躁

如何克服根域 CNAME 限制?

如何克服 Netezza 缺乏唯一约束/参照完整性执行的问题?