0

I'm new at dash and set-up a dashboard with a dropdown field, a graph and a table. All data comming from a database. Thats works fine and without a problem. However, I would like to filter the data via the dropdown list or by selection within the graph. The graph and table should only report selected data.

Within the published code, the callback is not included due to the fact that I don't know how to handle the filter mechanism.

Code:

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)

I would like to filter data by selection within the graph or selecting via dropdown list. Or both in combination.

Thx in advance

1 Answer 1

1

You need a callback that will look something like this, depending on your dataframe:

@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!')
    )
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! That is what I'm looking for. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.