通过下拉列表和图表进行回调过滤

Callback filtering via dropdown and graph

我是 dash 的新手,我设置了一个带有下拉字段、图表和 table 的仪表板。来自数据库的所有数据。多数民众赞成在工作正常,没有问题。但是,我想通过下拉列表或图表中的选择来过滤数据。该图表和 table 应该只报告选定的数据。

在已发布的代码中,由于我不知道如何处理过滤器机制,因此未包含回调。

代码:

from Dash_helper import *
import datetime
import dash_table
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import re

v_sql = "SELECT * FROM tbl_testdata;"

df = pd.read_sql_query(v_sql, local_db)

def generate_graph(dataframe):
    return dcc.Graph(
        id='example-graph',
        figure={
            'data': [
                {'x': dataframe["date"], 'y': dataframe["amount"], 'type': 'bar', 'name': '???'},
            ],
            'layout': {
                'title': 'This is a title!'
            }
        }
    )

def generate_table(dataframe, max_rows=12):
    return html.Table(
        #Header
        [html.Tr([html.Th(col) for col in dataframe.columns])] +

        #Body
        [html.Tr([
            html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
        ]) for i in range(min(len(dataframe), max_rows))]
    )

app = dash.Dash(__name__)

app.layout = html.Div(children=[
    html.H4(children='Headerline to be defined'),
    dcc.Dropdown(
        id='my-dropdown',
        options=[
            {'label': '2018', 'value': '2018'},
            {'label': '2019', 'value': '2019'}
        ],
        value='2019'
    ),
    html.Div(id='output-container'),
    generate_graph(df),
    generate_table(df)
])

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

我想通过在图表中选择或通过下拉列表选择来过滤数据。或者两者结合。

提前致谢

您需要一个看起来像这样的回调,具体取决于您的数据帧:

@app.callback(
    Output('example-graph', 'figure'),
    [Input('my-dropdown', 'value')])
def my_callback_func(dropdown_value):
    df = pd.read_sql_query(v_sql, local_db)
    df = df[df['year'].eq(dropdown_value)]

    return dict(
        data=[{'x': df["date"], 'y': df["amount"], 'type': 'bar', 'name': '???'}],
        layout=dict('title': 'This is a title!')
    )