To display the components (dropdowns and graphs) in one row with three columns, we can use Dash’s built-in layout structure with html.Div and appropriate CSS styles. Below is the updated code:
Updated Code:
import dash
from dash import dcc, html, Input, Output
import pandas as pd
import plotly.express as px
# Load sample superstore data
data = {
'Category': ['Furniture', 'Furniture', 'Office Supplies', 'Office Supplies', 'Technology', 'Technology'],
'Sales': [100, 200, 150, 300, 400, 250],
'Region': ['East', 'West', 'East', 'West', 'East', 'West'],
'Sub-Category': ['Chairs', 'Tables', 'Binders', 'Pens', 'Phones', 'Computers'],
'Profit': [20, 50, 30, 100, 200, 150]
}
df = pd.DataFrame(data)
# Initialize Dash app
app = dash.Dash(__name__)
# Define the app layout
app.layout = html.Div([
html.H1("Superstore Dashboard", style={'text-align': 'center'}),
# Row layout: 3 columns
html.Div([
html.Div([
html.Label("Select Category:"),
dcc.Dropdown(
id='category-dropdown',
options=[{'label': cat, 'value': cat} for cat in df['Category'].unique()],
value='Furniture',
clearable=False
),
], style={'width': '30%', 'display': 'inline-block', 'padding': '10px'}),
html.Div([
html.Label("Select Region:"),
dcc.Dropdown(
id='region-dropdown',
options=[{'label': reg, 'value': reg} for reg in df['Region'].unique()],
value='East',
clearable=False
),
], style={'width': '30%', 'display': 'inline-block', 'padding': '10px'}),
], style={'display': 'flex', 'justify-content': 'space-around'}),
# Row layout: 3 columns for graphs
html.Div([
html.Div([
dcc.Graph(id='sales-profit-graph'),
], style={'width': '30%', 'display': 'inline-block', 'padding': '10px'}),
html.Div([
dcc.Graph(id='sub-category-sales-pie'),
], style={'width': '30%', 'display': 'inline-block', 'padding': '10px'}),
], style={'display': 'flex', 'justify-content': 'space-around'}),
])
# Define callbacks
@app.callback(
[Output('sales-profit-graph', 'figure'),
Output('sub-category-sales-pie', 'figure')],
[Input('category-dropdown', 'value'),
Input('region-dropdown', 'value')]
)
def update_graphs(selected_category, selected_region):
filtered_df = df[(df['Category'] == selected_category) & (df['Region'] == selected_region)]
# Bar chart for Sales vs Profit
fig1 = px.bar(
filtered_df,
x='Sub-Category',
y=['Sales', 'Profit'],
title=f"Sales and Profit by Sub-Category in {selected_region}",
barmode='group'
)
# Pie chart for Sales distribution by Sub-Category
fig2 = px.pie(
filtered_df,
names='Sub-Category',
values='Sales',
title=f"Sales Distribution by Sub-Category in {selected_region}"
)
return fig1, fig2
# Run the app
if __name__ == '__main__':
app.run_server(debug=True)
Explanation:
- Dropdowns in One Row:
- Each dropdown (
category-dropdownandregion-dropdown) is placed inside ahtml.Divwith a width of 30%. - CSS styles (
display: inline-blockandpadding) ensure they are displayed in a single row.
- Each dropdown (
- Graphs in One Row:
- Each graph is placed inside its own
html.Divwith a width of 30%. - CSS styles (
display: inline-blockandpadding) ensure they appear side by side.
- Each graph is placed inside its own
- Flexbox Layout:
- The outer
html.Divusesdisplay: flexandjustify-content: space-aroundto align the components in one row and distribute space evenly.
- The outer
Output:
- First Row: Dropdowns for “Category” and “Region”.
- Second Row: Two graphs (bar chart and pie chart) displayed side by side.
What is DCC?
dcc stands for Dash Core Components, a module provided by the Dash library. It contains a collection of interactive components like graphs, dropdowns, sliders, and more, which are commonly used in Dash applications to build interactive dashboards.
Key Features of dcc:
- Provides user interface (UI) elements that are dynamic and reactive.
- These elements trigger callbacks to update data visualizations or other components.
- Works seamlessly with Dash’s Python-based callbacks for interactivity.
Common dcc Components:
dcc.Graph:- Displays interactive Plotly graphs.
- Example: Line charts, bar charts, scatter plots, etc.
- Used to embed visualizations in the Dash app.
- Example:
dcc.Graph(id='my-graph', figure=my_figure)
dcc.Dropdown:- Creates a dropdown menu for selecting options.
- Example:
dcc.Dropdown( id='my-dropdown', options=[ {'label': 'Option 1', 'value': 'opt1'}, {'label': 'Option 2', 'value': 'opt2'} ], value='opt1' )
dcc.Slider:- Provides a slider input for selecting a numeric range or value.
- Example:
dcc.Slider( id='my-slider', min=0, max=100, step=1, value=50 )
dcc.Input:- Allows for text or number input.
- Example:
dcc.Input( id='my-input', type='text', placeholder='Enter text here...' )
dcc.Tabs:- Creates a tabbed interface for switching between views.
- Example:
dcc.Tabs(id="tabs", value='tab-1', children=[ dcc.Tab(label='Tab 1', value='tab-1'), dcc.Tab(label='Tab 2', value='tab-2'), ])
Why Use dcc?
dcc simplifies building rich and interactive web dashboards with just Python code. It handles user interactions and makes it easy to link those interactions to backend logic via Dash callbacks.
Where is update_graphs Function called?
The update_graphs function is not called explicitly in the code by you. Instead, it is automatically called by Dash when the inputs (category-dropdown and region-dropdown) change, thanks to Dash’s callback mechanism.
Here’s how it works:
Callback Mechanism in Dash:
- Callback Decoration: The
@app.callbackdecorator binds theupdate_graphsfunction to specific inputs and outputs.@app.callback( [Output('sales-profit-graph', 'figure'), Output('sub-category-sales-pie', 'figure')], [Input('category-dropdown', 'value'), Input('region-dropdown', 'value')] )- Outputs: The components that the function updates (in this case, the
figureproperty ofsales-profit-graphandsub-category-sales-pie). - Inputs: The components that trigger the function when their values change (in this case, the
valueproperty ofcategory-dropdownandregion-dropdown).
- Outputs: The components that the function updates (in this case, the
- Triggering the Callback: Whenever the user interacts with the dropdowns (
category-dropdownorregion-dropdown), theirvalueproperty changes. This triggers Dash to automatically callupdate_graphs, passing the new dropdown values as arguments. - Function Execution: The
update_graphsfunction processes the inputs (selected_categoryandselected_region), generates the updated figures, and returns them. - Updating Components: The returned figures are assigned to the
figureproperties ofsales-profit-graphandsub-category-sales-pie, updating the visualizations on the dashboard.
Key Point:
You don’t need to explicitly call the update_graphs function. Dash handles this for you as part of its reactive architecture.
Let me know if you’d like more details about how Dash callbacks work!
