If you’ve ever wanted to build an interactive dashboard in Python without dealing with frontend code, Dash is the tool you need. Dash is a powerful and easy-to-use framework that allows you to create interactive web apps with dynamic data visualizations. In this article, you’ll learn how to build an interactive dashboard from scratch, connect it to a database, and visualize your data easily using Plotly.
What is Dash?
Dash is a Python framework created by Plotly for building interactive web applications focused on data visualization. With Dash, you can create dashboards with interactive charts without writing complex frontend code. It supports a high level of interactivity, making it ideal for real-time data analysis.
One of Dash’s biggest advantages is that it allows you to work entirely in Python using Plotly to create advanced visualizations—no need to learn HTML, CSS, or JavaScript. That makes Dash perfect for both developers and data analysts alike.
Why Use Dash?
Here are a few reasons to consider Dash for your next data project:
Ease of use: Building interactive dashboards is simple and straightforward.
Interactivity: Add callbacks to make charts react to user inputs in real time.
Flexibility: Integrate with multiple data sources, including SQL databases, Excel, and CSV files.
Scalability: From simple apps to complex analytical dashboards—Dash grows with your needs.
In short, Dash is ideal for anyone looking to create dynamic, custom data visualizations with minimal complexity.
Archivos del Proyecto:
- app.py: This file contains the logic of the Dash application.
- config.py: Holds the credentials and configuration for the database connection.
- requirements.txt: Lists all the dependencies required to run the project.
📦 Step 1: Install Dependencies
First, make sure you have all required libraries installed. Create a requirements.txt file like this:
dash
pandas
mysql-connector-python
plotly
Then, install everything with:
pip install -r requirements.txt
🔌 Step 2: Connect to a MySQL Database
We'll use MySQL as our data source. You’ll need to configure your database connection in config.py like this:
# config.py
DB_CONFIG = {
"host": "localhost",
"user": "root",
"password": "",
"database": "tienda_ventas"
}
Now, in your app.py, write a function to fetch the data:
# app.py
import dash
from dash import html, dcc
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd
import mysql.connector
from config import DB_CONFIG # Usamos config para la conexiĂłn
def get_data():
conn = mysql.connector.connect(
host=DB_CONFIG["host"],
user=DB_CONFIG["user"],
password=DB_CONFIG["password"],
database=DB_CONFIG["database"]
)
query = """
SELECT p.nombre AS producto, p.categoria, p.precio, v.cantidad, v.fecha
FROM ventas v
JOIN productos p ON v.producto_id = p.id
"""
df = pd.read_sql(query, conn)
conn.close()
return df
# Obtener datos
df = get_data()
We use mysql.connector.connect() to connect, and pd.read_sql() to query and load data into a Pandas DataFrame.
🛠️ Step 3: Build the Dash App
Let’s build the actual dashboard. We'll use a dropdown to select product categories, a line chart for daily sales, and a bar chart for total sales by product.
# app.py
# Crear app
app = dash.Dash(__name__)
app.title = "Dashboard de Ventas"
# Layout
app.layout = html.Div([
html.H1("📊 Dashboard de Ventas", style={'textAlign': 'center'}),
dcc.Dropdown(
id='categoria-dropdown',
options=[{'label': cat, 'value': cat} for cat in df['categoria'].unique()],
value=df['categoria'].unique()[0],
style={'width': '50%', 'margin': 'auto'}
),
dcc.Graph(id='grafico-ventas'),
html.Hr(),
dcc.Graph(
figure=px.bar(
df.groupby('producto')['cantidad'].sum().reset_index(),
x='producto',
y='cantidad',
title="Ventas totales por producto"
)
)
])
@app.callback(
Output('grafico-ventas', 'figure'),
Input('categoria-dropdown', 'value')
)
def update_graph(categoria):
filtrado = df[df['categoria'] == categoria]
fig = px.line(filtrado, x='fecha', y='cantidad', color='producto',
title=f"Ventas por dĂa - CategorĂa: {categoria}")
return fig
# Ejecutar
if __name__ == '__main__':
app.run(debug=True)
Code Breakdown
Dropdown: Users select a product category; charts update based on this selection.
Line Chart: Shows daily sales per product in the selected category.
Bar Chart: Displays total units sold per product.
To run your dashboard locally, simply run the app.py file:
archivo app.py
After a few seconds, you'll see this in your terminal:
Running on http://127.0.0.1:8050/
Open that URL in your browser, and voilà ! 🎉 You’ll see your fully functional dashboard in action.
Top comments (1)
Good, but elaborate more on your ideas.