🧠 PYTHON TIP + DASH: Smart Filters with Dependent Dropdowns

🧠 PYTHON TIP + DASH: Smart Filters with Dependent Dropdowns

📰 Edição #44 — PYTHON TIP + DASH: Smart Filters with Dependent Dropdowns

Article content

1. ✨ Opening Sentence

Have you ever imagined your dashboard guiding the user only through valid and logical paths? With dependent filters, that's entirely possible!


2. ✅ Tip Objective

Teach how to create dynamic and chained dropdowns using Dash, ensuring the options shown are always consistent with previous selections.


3. 📚 Technical Concept

Dependent dropdowns are filters whose available options change dynamically based on another filter's selection. This is achieved using callbacks that update layout components based on multiple Input and Output.


4. 💡 Python Representation

We use the Dash (Plotly) library to compose the web interface and reactive filters. Smart control is handled via callbacks between selectors.


5. 🧪 Python Script with Comments

import dash
from dash import dcc, html, Input, Output
import pandas as pd
import plotly.express as px


# ========================

# 🔢 SIMULATED DATA

# ========================

categories = {

    'Electronics': ['Smartphone', 'Notebook', 'TV'],

    'Furniture': ['Chair', 'Table', 'Cabinet'],

    'Clothing': ['Shirt', 'Pants', 'Jacket']

}


stock_levels = {

    'Smartphone': 25, 'Notebook': 12, 'TV': 7,

    'Chair': 40, 'Table': 15, 'Cabinet': 9,

    'Shirt': 100, 'Pants': 80, 'Jacket': 45

}


# ========================

# 🚀 DASH APP

# ========================

app = dash.Dash(__name__)

app.title = "Dependent Dropdowns with Stock Chart"


# ========================

# 🎨 LAYOUT

# ========================

app.layout = html.Div([

    html.H2("Dependent Dropdowns with Stock Chart", style={"textAlign": "center"}),


    html.Div([

        html.Div([

            html.Label("Category", style={'fontWeight': 'bold'}),

            dcc.Dropdown(

                id='dropdown-category',

                options=[{'label': k, 'value': k} for k in categories],

                value='Electronics',

                clearable=False

            )

        ], style={'flex': '1', 'marginRight': '20px'}),


        html.Div([

            html.Label("Model", style={'fontWeight': 'bold'}),

            dcc.Dropdown(

                id='dropdown-model',

                clearable=False

            )

        ], style={'flex': '1'})

    ], style={'display': 'flex', 'width': '60%', 'margin': '0 auto', 'padding': '40px 0'}),


    html.Div([

        dcc.Graph(id='stock-graph')

    ], style={'width': '50%', 'margin': '0 auto'})

])

 
# ========================

# CALLBACKS

# ========================

@app.callback(

    Output('dropdown-model', 'options'),

    Output('dropdown-model', 'value'),

    Input('dropdown-category', 'value')

)

def update_model_dropdown(category):

    models = categories.get(category, [])

    options = [{'label': m, 'value': m} for m in models]

    default_value = models[0] if models else None

    print(f"[DEBUG] Category: {category} → Models: {models}")

    return options, default_value

 

@app.callback(

    Output('stock-graph', 'figure'),

    Input('dropdown-model', 'value')

)

def update_stock_chart(model):

    if not model or model not in stock_levels:

        return px.bar(title="Select a valid model")


    # Create DataFrame for compatibility with px.bar

    df = pd.DataFrame({'Model': [model], 'Stock': [stock_levels[model]]})


    fig = px.bar(

        df,

        x='Model',

        y='Stock',

        text='Stock',

        title=f"Stock Level for: {model}",

        labels={'Stock': 'Units in Stock'}

    )


    fig.update_traces(textposition='outside')

    fig.update_layout(

        yaxis=dict(range=[0, max(stock_levels.values()) * 1.1])

    )

    return fig


# ========================

# RUN

# ========================

if name == '__main__':

    app.run(debug=True)        

6. 🖼️ Generated Images

Article content
Article content
Article content

7. 📊 Script Explanation

This code creates a filter system that guides the user from Category to Model — always respecting the available data and selections already made.


8. 🛠️ Practical Applications

• Budget planning dashboards • Filters in CRM systems • Performance analysis by unit/category • Interactive BI reports


9. 🌐 Integration with Power BI

You can embed this Dash app directly into Power BI Service using an <iframe>:

<iframe src="https://your-dash-app.com" width="100%" height="600"></iframe>

  1. Deploy your app (Heroku, Render, Azure)
  2. In Power BI, use a "Web Content" block
  3. Paste the link and adjust the iframe dimensions


10. 💼 Real-World Example

Imagine a budget dashboard: the user selects the fiscal year, then the business unit, and finally the cost center. Each step reduces errors and makes the experience intuitive.


11. 💬 EXTRA TIP

Want to make the dropdown even smarter? Add placeholder, set disabled=True until data loads, and use dash.no_update to avoid errors during callbacks.


12. 📅 CTA – Keep Exploring!

Want to turn your spreadsheets into smart visual tools? Explore more tips like this:

💼 LinkedIn & Newsletters:

👉 https://www.garudax.id/in/izairton-oliveira-de-vasconcelos-a1916351/

👉 https://www.garudax.id/newsletters/scripts-em-python-produtividad-7287106727202742273

👉 https://www.garudax.id/build-relation/newsletter-follow?entityUrn=7319069038595268608

💼 Company Page:

👉 https://www.garudax.id/company/106356348/

💻 GitHub:

👉 https://github.com/IOVASCON


13. 🔁 Filter Connectivity

Each dropdown acts as a sequential input — reducing invalid choices, improving user experience, and making the dashboard more reliable.


14. 🧠 Strategic Benefit

Dependent dropdowns enhance dashboard usability and drastically reduce filter conflicts or user mistakes.


15. 🏷️ Hashtags

#Python #Dash #DynamicDropdowns #SmartDashboards #PowerBI #DataVisualization #PythonForProductivity

To view or add a comment, sign in

Others also viewed

Explore content categories