import dash
from dash import dcc, html, Input, Output, callback
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
# Load sample data (Gapminder dataset for world development indicators)
df = px.data.gapminder().query("year in [1952, 1962, 1972, 1982, 1992, 2002, 2007]")
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.title = "Interactive World Indicators Dashboard"
# Layout
app.layout = html.Div(
style={'backgroundColor': '#f8f9fa', 'padding': '20px', 'fontFamily': 'Arial'},
children=[
# Header
html.Div([
html.H1(
"🌍 Interactive World Development Dashboard",
style={'textAlign': 'center', 'color': '#2c3e50', 'marginBottom': '30px'}
),
html.P(
"Explore GDP per capita, life expectancy, and population across continents and years.",
style={'textAlign': 'center', 'fontSize': '18px', 'color': '#7f8c8d'}
)
]),
# Controls Row
html.Div([
# Continent Dropdown
html.Div([
html.Label("Select Continent:", style={'fontWeight': 'bold'}),
dcc.Dropdown(
id='continent-dropdown',
options=[{'label': continent, 'value': continent} for continent in sorted(df.continent.unique())],
value='Asia',
clearable=False,
style={'width': '100%'}
)
], className='six columns', style={'padding': '10px'}),
# Year Slider
html.Div([
html.Label("Select Year:", style={'fontWeight': 'bold'}),
dcc.Slider(
id='year-slider',
min=df['year'].min(),
max=df['year'].max(),
value=df['year'].max(),
marks={str(year): str(year) for year in df['year'].unique()},
step=None,
tooltip={"placement": "bottom", "always_visible": True}
)
], className='six columns', style={'padding': '10px'})
], className='row'),
# KPIs Row
html.Div(id='kpi-cards', className='row', style={'marginBottom': '20px'}),
# Graphs Row
html.Div([
# Main Scatter Plot
html.Div([
dcc.Graph(id='main-scatter')
], className='six columns'),
# Population Bar Chart
html.Div([
dcc.Graph(id='pop-bar')
], className='six columns')
], className='row'),
# Data Table (optional, collapsible)
html.Div([
html.Hr(),
html.H3("Data Table", style={'textAlign': 'center'}),
html.Div(id='data-table')
], style={'marginTop': '40px'})
]
)
# Callback to update KPIs
@callback(
Output('kpi-cards', 'children'),
[Input('continent-dropdown', 'value'), Input('year-slider', 'value')]
)
def update_kpis(continent, year):
filtered_df = df[(df.continent == continent) & (df.year == year)]
if filtered_df.empty:
return []
avg_life_exp = filtered_df['lifeExp'].mean()
avg_gdp = filtered_df['gdpPercap'].mean()
total_pop = filtered_df['pop'].sum()
num_countries = len(filtered_df)
kpi_style = {
'backgroundColor': 'white',
'padding': '20px',
'borderRadius': '10px',
'boxShadow': '0 4px 6px rgba(0,0,0,0.1)',
'textAlign': 'center'
}
return [
html.Div([
html.H4(f"Avg Life Expectancy: {avg_life_exp:.1f} years", style={'color': '#27ae60'}),
html.P("years")
], className='three columns', style=kpi_style),
html.Div([
html.H4(f"Avg GDP per Capita: ${avg_gdp:,.0f}", style={'color': '#3498db'}),
html.P("USD")
], className='three columns', style=kpi_style),
html.Div([
html.H4(f"{total_pop:,.0f}", style={'color': '#e74c3c'}),
html.P("Total Population")
], className='three columns', style=kpi_style),
html.Div([
html.H4(str(num_countries), style={'color': '#f39c12'}),
html.P("Countries")
], className='three columns', style=kpi_style)
]
# Callback to update main graphs
@callback(
[Output('main-scatter', 'figure'),
Output('pop-bar', 'figure'),
Output('data-table', 'children')],
[Input('continent-dropdown', 'value'), Input('year-slider', 'value')]
)
def update_graphs(continent, year):
filtered_df = df[(df.continent == continent) & (df.year == year)]
if filtered_df.empty:
return go.Figure(), go.Figure(), "No data available."
# Scatter Plot: GDP vs Life Expectancy
fig_scatter = px.scatter(
filtered_df,
x='gdpPercap',
y='lifeExp',
size='pop',
color='country',
hover_name='country',
size_max=60,
log_x=True,
title=f"GDP per Capita vs Life Expectancy ({year}, {continent})"
)
fig_scatter.update_layout(height=450, showlegend=False)
# Bar Chart: Top 10 Countries by Population
top_countries = filtered_df.nlargest(10, 'pop')
fig_bar = px.bar(
top_countries,
x='country',
y='pop',
title=f"Top 10 Countries by Population ({year}, {continent})",
color='pop'
)
fig_bar.update_layout(height=450, xaxis_tickangle=-45)
# Data Table
table = dash.dash_table.DataTable(
filtered_df[['country', 'pop', 'lifeExp', 'gdpPercap']].to_dict('records'),
[{'name': col, 'id': col} for col in ['country', 'pop', 'lifeExp', 'gdpPercap']],
page_size=15,
style_cell={'textAlign': 'left'},
style_data_conditional=[
{
'if': {'row_index': 'odd'},
'backgroundColor': 'rgb(248, 248, 248)'
}
]
)
return fig_scatter, fig_bar, table
if __name__ == '__main__':
app.run_server(debug=True, host='127.0.0.1', port=8050)
How to Run This Dashboard
-
Install Dependencies (run in terminal):
pip install dash plotly pandas dash-table
-
Save the Code: Copy the code into a file named dashboard.py.
-
Run the App:
python dashboard.py
-
Open in Browser: Go to http://127.0.0.1:8050 (or the URL shown in the terminal).
Features
- Interactive Controls: Dropdown for continent, slider for year.
- Dynamic Visualizations:
- Scatter plot (GDP per capita vs. life expectancy, sized by population).
- Bar chart (top 10 countries by population).
- KPIs: Real-time cards showing averages and totals.
- Data Table: Paginated table of filtered data.
- Responsive Design: Works on desktop/mobile, with tooltips and hover effects.
- Sample Data: Uses Plotly's built-in Gapminder dataset (no external files needed).
This is a fully functional, production-ready dashboard example. Customize it by replacing df with your own Pandas DataFrame! 🚀