import plotly.express as px
import pandas as pd
import plotly.graph_objects as go
import dash
from dash import Dash, dcc, html, callback, Input, Output, State
import dash_bootstrap_components as dbc
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
oecd_df = (pd.read_csv('oecd_wellbeing_clean.csv',
usecols=['Year','Country', 'Age', 'Sex', 'Education', 'Domain', 'Measure','OBS_VALUE']))
# Obtener listas únicas para los dropdowns
available_years = sorted(oecd_df['Year'].unique())
available_domains = sorted(oecd_df['Domain'].unique())
available_countries = sorted(oecd_df['Country'].unique())
available_demographics = ['Age', 'Sex', 'Education']
# Definir los colores personalizados con tonos más tenues y elegantes
COLORS = {
"primary": "#507B9C", # Azul medio tenue
"primary-light": "#E2EBF3", # Azul muy claro (fondo)
"secondary": "#6D9775", # Verde tenue
"secondary-light": "#E5F0E7", # Verde muy claro
"accent": "#BA8057", # Marrón/naranja suave
"accent-light": "#F5EBE0", # Beige claro
"sidebar-bg": "#F7F9FC", # Gris azulado muy claro
"card-bg": "#FFFFFF", # Blanco para tarjetas
"text-primary": "#2C3E50", # Azul oscuro para texto
"text-secondary": "#5D6D7E" # Gris azulado para texto secundario
}
# Diccionario con descripciones para tooltips mejorados con estilo storytelling
domain_descriptions = {
"Civic Engagement": "The heartbeat of democracy and community involvement. This domain explores how citizens shape their societies through participation, trust in institutions, and engagement with governance systems.",
"Health": "Beyond the absence of illness, this domain tells the story of our collective well-being: how long we live, how well we live, and the physical and mental resources we have to thrive.",
"Safety": "The foundation of peaceful societies. This domain reveals how secure people feel in their daily lives, exploring crime rates, perception of safety, and the invisible social contracts that keep communities stable.",
"Social Connections": "The invisible threads that bind us together. This domain maps our relationships, support networks, and the social fabric that catches us when we fall and celebrates with us when we rise.",
"Subjective Well-being": "The story as told by people themselves. This domain captures how satisfied people are with their lives, their emotional states, and their personal assessment of what makes life worthwhile.",
"Work and Job Quality": "More than just making a living. This domain explores the quality of our working lives, from fair compensation to workplace safety, job security, and the opportunity to use our talents.",
"Work-Life Balance": "The delicate dance between professional and personal life. This domain examines how people navigate time constraints, manage family responsibilities, and find space for leisure and rest."
}
# Crear un tooltip genérico para medidas con estilo storytelling
measure_tooltip = "Every number tells a story. This indicator captures a specific chapter in the larger narrative of well-being, measuring concrete aspects that impact people's lives daily."
# Inicializar la app con el tema Bootstrap FLATLY
app = Dash(__name__, external_stylesheets=[dbc.themes.FLATLY, 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css', 'style.css'])
app.title = "OECD Well-being Dashboard - Stories Behind the Numbers"
# Definir estilo CSS personalizado
custom_css = {
"body": {
"backgroundColor": COLORS["primary-light"],
"color": COLORS["text-primary"],
"fontFamily": "'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"
}
}
# Create ML clustering function
def cluster_countries(df, domain, measure, year, n_clusters=3):
"""
Cluster countries based on selected measure values
"""
# Filter data for the specific domain, measure and year
filtered_df = df[(df['Domain'] == domain) &
(df['Measure'] == measure) &
(df['Year'] == year) &
(df['Age'] == 'Total') &
(df['Sex'] == 'Total') &
(df['Education'] == 'Total')]
# If not enough data, return empty results
if len(filtered_df) < n_clusters:
return pd.DataFrame(), {}
# Prepare data for clustering
pivot_df = filtered_df.pivot_table(
index='Country', values='OBS_VALUE', aggfunc='mean'
).reset_index()
# For real clustering we'd use multiple features, but for simplicity we'll use just one
X = pivot_df[['OBS_VALUE']].values
# Standardize features
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Perform clustering
kmeans = KMeans(n_clusters=n_clusters, random_state=42)
pivot_df['Cluster'] = kmeans.fit_predict(X_scaled)
# Get cluster centers
centers = scaler.inverse_transform(kmeans.cluster_centers_)
# Create cluster labels
cluster_labels = {}
centers_sorted = sorted([(i, centers[i][0]) for i in range(n_clusters)], key=lambda x: x[1])
labels = ["Lower performers", "Mid-range performers", "Higher performers"]
for i, (cluster_idx, _) in enumerate(centers_sorted):
if i < len(labels):
cluster_labels[cluster_idx] = labels[i]
return pivot_df, cluster_labels
# Function to predict future values
def predict_future_values(df, domain, measure, country, demographic_type, demographic_value, years_to_predict=2):
"""
Predict future values using simple linear regression
"""
# Filter data
filtered_df = df[(df['Domain'] == domain) &
(df['Measure'] == measure) &
(df['Country'] == country) &
(df[demographic_type] == demographic_value)]
# If not enough data points, return empty results
if len(filtered_df) < 3: # Need at least 3 points for meaningful prediction
return None, None
# Prepare training data
X = filtered_df['Year'].values.reshape(-1, 1)
y = filtered_df['OBS_VALUE'].values
# Fit model
model = LinearRegression()
model.fit(X, y)
# Create future years
last_year = max(filtered_df['Year'])
future_years = np.array(range(last_year + 1, last_year + years_to_predict + 1))
# Predict
future_X = future_years.reshape(-1, 1)
predictions = model.predict(future_X)
return future_years, predictions
# Crear el componente de tooltip informativo con estilo storytelling
def create_tooltip(id, text):
return html.Div([
html.I(className="fas fa-info-circle me-2", id=f"tooltip-{id}"),
dbc.Tooltip(text, target=f"tooltip-{id}", placement="right")
], className="d-inline-block ms-2")
# Crear los componentes de la sidebar con nuevo estilo
sidebar = dbc.Card([
html.H4([html.I(className="fas fa-sliders-h me-2"), "Well-being Navigator:"],
className="card-header",
style={"backgroundColor": COLORS["primary"], "color": "white"}),
dbc.CardBody([
html.Div([
html.Label([
html.I(className="fas fa-th me-2"), "Well-being Domain",
create_tooltip("domain", "Choose which chapter of the well-being story you want to explore.")
]),
dcc.Dropdown(
id='domain-dropdown',
options=[{'label': d, 'value': d} for d in available_domains],
value= "Work and job quality",
placeholder="Select a Domain",
className="mb-3"
),
]),
html.Div([
html.Label([
html.I(className="fas fa-chart-bar me-2"), "Story Indicator",
create_tooltip("measure", measure_tooltip)
]),
dcc.Dropdown(
id='measure-dropdown',
options=[],
value=["Employment rate"],
placeholder="Select a Measure",
className="mb-3"
),
]),
html.Div([
html.Label([
html.I(className="fas fa-users me-2"), "Population Lens",
create_tooltip("demographic", "Focus your story on different segments of society - by age, gender, or education level.")
]),
dcc.Dropdown(
id='demographic-dropdown',
options=[{'label': demo, 'value': demo} for demo in available_demographics],
value='Sex',
placeholder="Select a demographic group.",
className="mb-3"
),
]),
html.Div([
html.Label([
html.I(className="fas fa-globe-americas me-2"), "Nations in Focus",
create_tooltip("countries", "Choose which countries' stories you want to compare.")
]),
dcc.Dropdown(
id='country-dropdown',
options=[{'label': country, 'value': country} for country in available_countries],
value=['Austria', 'Belgium'],
multi=True,
placeholder="Select one or more countries",
className="mb-3"
),
]),
html.Div([
html.Label([html.I(className="fas fa-film me-2"), "Narrative View"], className="fw-bold mt-3 mb-2"),
dbc.RadioItems(
id="time-view-selector",
options=[
{"label": "Snapshot (One Year)", "value": "single"},
{"label": "Journey (Time Series)", "value": "series"}
],
value="single",
inline=True,
className="mb-2"
),
]),
html.Div(id="year-selector-container", children=[
html.Label([
html.I(className="fas fa-calendar-alt me-2"), "Year in Focus",
create_tooltip("year", "Select a moment in time for your snapshot.")
]),
dcc.Dropdown(
id='year-dropdown',
options=[{'label': str(year), 'value': year} for year in available_years],
value=2020,
placeholder="Select a Year",
className="mb-3"
),
]),
html.Div(id="year-range-container", style={"display": "none"}, children=[
html.Label([
html.I(className="fas fa-calendar-week me-2"), "Timeline",
create_tooltip("year-range", "Choose the historical period for your narrative.")
]),
dcc.RangeSlider(
id='year-range-slider',
min=min(available_years) if len(available_years) > 0 else 2000,
max=max(available_years) if len(available_years) > 0 else 2020,
value=[min(available_years) if len(available_years) > 0 else 2000,
max(available_years) if len(available_years) > 0 else 2020],
marks={int(year): str(int(year)) for year in available_years[::3]},
className="mb-3"
),
]),
dbc.Checklist(
id='include-total-checkbox',
options=[{'label': ' Include Population Totals', 'value': 'Total'}],
value=['Total'],
inline=True,
className="mb-3"
),
html.Hr(),
# Advanced Analytics Section (New)
html.H5([html.I(className="fas fa-brain me-2"), "Smart Insights"], className="mt-3 mb-2"),
dbc.Button(
[html.I(className="fas fa-object-group me-2"), "Cluster Analysis"],
id="show-clusters-button",
color="secondary",
outline=True,
className="mb-2 me-2",
size="sm",
style={"borderColor": COLORS["secondary"], "color": COLORS["secondary"]}
),
dbc.Button(
[html.I(className="fas fa-chart-line me-2"), "Future Trends"],
id="show-predictions-button",
color="accent",
outline=True,
className="mb-2",
size="sm",
style={"borderColor": COLORS["accent"], "color": COLORS["accent"]}
),
html.Hr(),
# Mini glosario desplegable
dbc.Button(
[html.I(className="fas fa-book-open me-2"), "Story Guide"],
id="collapse-button",
className="mb-3",
color="primary",
outline=True,
style={"borderColor": COLORS["primary"], "color": COLORS["primary"]}
),
dbc.Collapse(
dbc.Card(dbc.CardBody([
html.H5("The Language of Well-being"),
html.P([html.Strong("OECD: "), "Organisation for Economic Cooperation and Development – the storytellers behind this data"]),
html.P([html.Strong("Domain: "), "A chapter in the well-being story – health, work, connections with others"]),
html.P([html.Strong("Indicator: "), "The specific characters and plot points that make each chapter unique"]),
html.P([html.Strong("OBS_VALUE: "), "The numbers that quantify human experience and well-being"])
])),
id="collapse",
is_open=False,
),
]),
], className="shadow-sm h-100", style={"backgroundColor": COLORS["sidebar-bg"], "borderColor": COLORS["primary-light"]})
# Diseño principal de la aplicación
app.layout = dbc.Container([
# Estilos globales
html.Div([
html.Link(
rel='stylesheet',
href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css'
),
]),
dbc.Navbar([
dbc.Container([
html.A(
dbc.Row([
dbc.Col(html.I(className="fas fa-map-marked-alt", style={"color": COLORS["secondary-light"]})),
dbc.Col(dbc.NavbarBrand("OECD Well-being Dashboard", className="ms-2",style={"fontSize": "2.0rem"})),
], align="center", className="g-0"),
href="#",
style={"textDecoration": "none"},
),
], fluid=True)
], color=COLORS["primary"], dark=True, className="mb-4 shadow-sm"),
dbc.Row([
# Sidebar
dbc.Col(sidebar, width=3, className="mb-4"),
# Área principal de contenido
dbc.Col([
dbc.Card([
dbc.CardHeader(html.H4(id="chart-title", children="Well-being Explorer"),
style={"backgroundColor": COLORS["primary-light"], "color": COLORS["text-primary"]}),
dbc.CardBody([
# Insight summary - new storytelling element
html.Div(id="insight-summary", className="story-callout mb-3"),
dbc.Tabs([
dbc.Tab(
dcc.Graph(id='comparison-graph', className="h-100"),
label=" Comparison Snapshot",
tab_id="bar-tab",
label_style={"color": COLORS["text-secondary"]},
active_label_style={"color": COLORS["primary"], "fontWeight": "bold"}
),
dbc.Tab(
dcc.Graph(id='time-series-graph', className="h-100"),
label="Historical Journey",
tab_id="time-tab",
label_style={"color": COLORS["text-secondary"]},
active_label_style={"color": COLORS["primary"], "fontWeight": "bold"}
),
# New tabs for ML insights
dbc.Tab(
dcc.Graph(id='clusters-graph', className="h-100"),
label="Country Clusters",
tab_id="clusters-tab",
label_style={"color": COLORS["text-secondary"]},
active_label_style={"color": COLORS["secondary"], "fontWeight": "bold"}
),
dbc.Tab(
dcc.Graph(id='predictions-graph', className="h-100"),
label="Future Trends",
tab_id="predictions-tab",
label_style={"color": COLORS["text-secondary"]},
active_label_style={"color": COLORS["accent"], "fontWeight": "bold"}
),
], id="chart-tabs", active_tab="bar-tab", className="custom-tabs"),
], className="d-flex flex-column", style={"minHeight": "600px"}),
dbc.CardFooter(html.P(id="chart-note", children=[
html.I(className="fas fa-compass me-2"),
"Journey Source: OECD Better Life Index"
], className="text-muted", style={"color": COLORS["text-secondary"]}))
], className="shadow-sm h-100", style={"borderColor": COLORS["primary-light"]}),
], width=9),
]),
dbc.Row([
dbc.Col([
dbc.Card([
dbc.CardHeader(html.H5([
html.I(className="fas fa-lightbulb me-2"),
"The Story Behind the Numbers"
]), style={"backgroundColor": COLORS["secondary-light"], "color": COLORS["text-primary"]}),
dbc.CardBody(html.Div(id="interpretation-text"), style={"color": COLORS["text-secondary"]})
], className="shadow-sm mt-4", style={"borderColor": COLORS["secondary-light"]})
], width=12)
]),
# Modals for cluster and prediction explanations
dbc.Modal([
dbc.ModalHeader(html.H4("Country Clusters Explained")),
dbc.ModalBody([
html.P([
"Our smart analysis has identified patterns in the data and grouped countries into clusters based on their performance in this indicator. ",
"This reveals which nations share similar characteristics and challenges."
]),
html.Hr(),
html.H5("How to interpret the clusters:"),
html.Ul([
html.Li(html.Strong("Higher performers: "), "Countries with the strongest results in this indicator"),
html.Li(html.Strong("Mid-range performers: "), "Countries with average results"),
html.Li(html.Strong("Lower performers: "), "Countries with results below the average")
]),
html.P([
"These clusters are purely based on data patterns and should be interpreted alongside contextual factors ",
"like policy environments, historical context, and other socioeconomic conditions."
], className="text-muted mt-3")
]),
dbc.ModalFooter(
dbc.Button("Close", id="close-clusters-modal", className="ms-auto", color="primary")
),
], id="clusters-explanation-modal", is_open=False, size="lg"),
dbc.Modal([
dbc.ModalHeader(html.H4("Future Trends Explained")),
dbc.ModalBody([
html.P([
"Our predictive analysis projects how indicators might evolve in the coming years based on historical patterns. ",
"These projections use linear regression to extend existing trends."
]),
html.Hr(),
html.H5("How to interpret the predictions:"),
html.Ul([
html.Li("Solid lines show actual historical data"),
html.Li("Dashed lines show projected future values"),
html.Li("Shaded areas represent the margin of uncertainty")
]),
html.P([
"Remember that predictions are estimates based on past patterns and cannot account for unexpected events, ",
"policy changes, or other disruptions that might affect these trajectories."
], className="text-muted mt-3")
]),
dbc.ModalFooter(
dbc.Button("Close", id="close-predictions-modal", className="ms-auto", color="primary")
),
], id="predictions-explanation-modal", is_open=False, size="lg"),
# Footer with storytelling style
html.Footer(
dbc.Container([
html.P([
"Every number tells a human story. Dashboard crafted with ",
html.I(className="fas fa-heart text-danger"),
" using OECD data. © 2025"
], className="text-center", style={"color": COLORS["text-secondary"], "fontSize": "0.9rem"})
]),
className="mt-5 py-3 shadow-sm",
style={"backgroundColor": COLORS["primary-light"], "borderTop": f"1px solid {COLORS['primary-light']}"})
], fluid=True, className="mb-5")
# Callback para mostrar/ocultar el glosario
@callback(
Output("collapse", "is_open"),
[Input("collapse-button", "n_clicks")],
[State("collapse", "is_open")],
)
def toggle_collapse(n, is_open):
if n:
return not is_open
return is_open
# Callbacks for showing/hiding explanation modals
@callback(
Output("clusters-explanation-modal", "is_open"),
[Input("show-clusters-button", "n_clicks"), Input("close-clusters-modal", "n_clicks")],
[State("clusters-explanation-modal", "is_open")],
)
def toggle_clusters_modal(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@callback(
Output("predictions-explanation-modal", "is_open"),
[Input("show-predictions-button", "n_clicks"), Input("close-predictions-modal", "n_clicks")],
[State("predictions-explanation-modal", "is_open")],
)
def toggle_predictions_modal(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
# Callback para establecer la pestaña activa cuando se presionan los botones de análisis
@callback(
Output("chart-tabs", "active_tab"),
[Input("show-clusters-button", "n_clicks"),
Input("show-predictions-button", "n_clicks"),
Input("time-view-selector", "value")],
[State("chart-tabs", "active_tab")]
)
def set_active_tab(clusters_clicks, predictions_clicks, view_type, current_tab):
ctx = dash.callback_context
if not ctx.triggered:
if view_type == "single":
return "bar-tab"
else:
return "time-tab"
else:
button_id = ctx.triggered[0]["prop_id"].split(".")[0]
if button_id == "show-clusters-button":
return "clusters-tab"
elif button_id == "show-predictions-button":
return "predictions-tab"
elif button_id == "time-view-selector":
if view_type == "single":
return "bar-tab"
else:
return "time-tab"
return current_tab
# Callback para actualizar las opciones de medida basadas en el dominio seleccionado
@callback(
Output('measure-dropdown', 'options'),
Output('measure-dropdown', 'value'),
[Input('domain-dropdown', 'value')]
)
def update_measure_options(selected_domain):
if selected_domain:
domain_measures = sorted(oecd_df[oecd_df['Domain'] == selected_domain]['Measure'].unique())
options = [{'label': m, 'value': m} for m in domain_measures]
value = domain_measures[0] if len(domain_measures) > 0 else None
return options, value
return [], None
# Callback for toggling between year selector and year range based on time view
@callback(
Output("year-selector-container", "style"),
Output("year-range-container", "style"),
[Input("time-view-selector", "value")]
)
def toggle_year_selectors(view_type):
if view_type == "single":
return {"display": "block"}, {"display": "none"}
else:
return {"display": "none"}, {"display": "block"}
# Callback para actualizar el título del gráfico
@callback(
Output('chart-title', 'children'),
[Input('domain-dropdown', 'value'),
Input('measure-dropdown', 'value')]
)
def update_chart_title(domain, measure):
if domain and measure:
return f"🌟 {measure} in {domain}"
return "Well-being Data Explorer"
# Callback to update the insight summary with storytelling
@callback(
Output('insight-summary', 'children'),
[Input('domain-dropdown', 'value'),
Input('measure-dropdown', 'value'),
Input('year-dropdown', 'value'),
Input('country-dropdown', 'value'),
Input('demographic-dropdown', 'value')]
)
def update_insight_summary(domain, measure, year, countries, demographic):
if not domain or not measure or not year or not countries or not demographic:
return "Select parameters to explore well-being data."
country_phrase = ""
if len(countries) == 1:
country_phrase = f"{countries[0]}"
elif len(countries) == 2:
country_phrase = f"{countries[0]} and {countries[1]}"
else:
country_phrase = f"{len(countries)} selected countries"
summary_text = f"Data for {measure} in {domain} for {country_phrase} in {year}, analyzed by {demographic}."
return html.P(summary_text)
# Callback para generar el gráfico de comparación
@callback(
Output('comparison-graph', 'figure'),
[Input('domain-dropdown', 'value'),
Input('measure-dropdown', 'value'),
Input('year-dropdown', 'value'),
Input('country-dropdown', 'value'),
Input('demographic-dropdown', 'value'),
Input('include-total-checkbox', 'value')]
)
def update_comparison_graph(domain, measure, year, countries, demographic, include_total):
if not domain or not measure or not year or not countries or not demographic:
return go.Figure()
# Filter data
filtered_df = oecd_df[(oecd_df['Year'] == year) &
(oecd_df['Domain'] == domain) &
(oecd_df['Measure'] == measure) &
(oecd_df['Country'].isin(countries))]
# Filter by demographic and handle 'Total' differently
if 'Total' in include_total:
demographic_values = filtered_df[demographic].unique()
else:
demographic_values = [val for val in filtered_df[demographic].unique() if val != 'Total']
filtered_df = filtered_df[filtered_df[demographic].isin(demographic_values)]
# Create bar chart with improved styling
fig = px.bar(
filtered_df,
x='Country',
y='OBS_VALUE',
color=demographic,
barmode='group',
title=f"{measure} by {demographic} ({year})",
labels={'OBS_VALUE': 'Value', 'Country': 'Country'},
color_discrete_sequence=[COLORS["primary"], COLORS["secondary"], COLORS["accent"],
"#D68C45", "#8E6C8A", "#4F94B8", "#97AC3D"]
)
# Improve styling
fig.update_layout(
plot_bgcolor=COLORS["card-bg"],
paper_bgcolor=COLORS["card-bg"],
font_family="'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
font_color=COLORS["text-primary"],
legend_title_text="",
margin=dict(l=40, r=40, t=60, b=40),
hoverlabel=dict(
bgcolor=COLORS["primary-light"],
font_size=12,
font_family="'Segoe UI', Roboto"
),
title={
'text': f"<b>{measure}</b> by {demographic} ({year})",
'y':0.95,
'x':0.5,
'xanchor': 'center',
'yanchor': 'top',
'font': dict(size=18)
}
)
fig.update_traces(
hovertemplate='<b>%{x}</b><br>%{y:.2f}<extra></extra>'
)
# Add annotation with storytelling insights
if len(filtered_df) > 0:
max_country = filtered_df.loc[filtered_df['OBS_VALUE'].idxmax()]['Country']
max_value = filtered_df['OBS_VALUE'].max()
fig.add_annotation(
x=0.5,
y=-0.15,
xref="paper",
yref="paper",
text=f"<i>Story Insight:</i> {max_country} shows the highest value at {max_value:.2f}",
showarrow=False,
font=dict(
family="'Segoe UI', italic",
size=12,
color=COLORS["accent"]
),
align="center",
bgcolor=COLORS["accent-light"],
bordercolor=COLORS["accent"],
borderwidth=1,
borderpad=4
)
return fig
# Callback para generar el gráfico de series temporales
@callback(
Output('time-series-graph', 'figure'),
[Input('domain-dropdown', 'value'),
Input('measure-dropdown', 'value'),
Input('year-range-slider', 'value'),
Input('country-dropdown', 'value'),
Input('demographic-dropdown', 'value'),
Input('include-total-checkbox', 'value')]
)
def update_time_series_graph(domain, measure, year_range, countries, demographic, include_total):
if not domain or not measure or not year_range or not countries or not demographic:
return go.Figure()
# Filter data
filtered_df = oecd_df[(oecd_df['Year'] >= year_range[0]) &
(oecd_df['Year'] <= year_range[1]) &
(oecd_df['Domain'] == domain) &
(oecd_df['Measure'] == measure) &
(oecd_df['Country'].isin(countries))]
# Filter by demographic and handle 'Total' differently
if 'Total' in include_total:
demographic_values = ['Total']
else:
demographic_values = [val for val in filtered_df[demographic].unique() if val != 'Total']
filtered_df = filtered_df[filtered_df[demographic].isin(demographic_values)]
# Create line chart with improved styling
fig = px.line(
filtered_df,
x='Year',
y='OBS_VALUE',
color='Country',
line_dash=demographic,
markers=True,
title=f"{measure} Over Time ({year_range[0]}-{year_range[1]})",
labels={'OBS_VALUE': measure, 'Year': 'Year'},
color_discrete_sequence=[COLORS["primary"], COLORS["secondary"], COLORS["accent"],
"#D68C45", "#8E6C8A", "#4F94B8", "#97AC3D"]
)
# Improve styling
fig.update_layout(
plot_bgcolor=COLORS["card-bg"],
paper_bgcolor=COLORS["card-bg"],
font_family="'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
font_color=COLORS["text-primary"],
legend_title_text="",
margin=dict(l=40, r=40, t=60, b=80),
hoverlabel=dict(
bgcolor=COLORS["primary-light"],
font_size=12,
font_family="'Segoe UI', Roboto"
),
title={
'text': f"<b>{measure}</b> Historical Journey ({year_range[0]}-{year_range[1]})",
'y':0.95,
'x':0.5,
'xanchor': 'center',
'yanchor': 'top',
'font': dict(size=18)
}
)
fig.update_traces(
hovertemplate='<b>%{x}</b><br>%{y:.2f}<extra></extra>'
)
# Add dynamic annotation with trend insights
if len(filtered_df) > 0:
# Try to find a meaningful trend insight
trend_text = ""
# Check if we have enough years to analyze trends
if len(filtered_df['Year'].unique()) > 2:
# Find country with biggest improvement
pivot_df = filtered_df[filtered_df[demographic] == 'Total'].pivot_table(
index='Country', values='OBS_VALUE', aggfunc=lambda x: x.iloc[-1] - x.iloc[0]
).reset_index()
if len(pivot_df) > 0:
max_improve_country = pivot_df.iloc[pivot_df['OBS_VALUE'].argmax()]['Country']
max_improve_value = pivot_df['OBS_VALUE'].max()
if max_improve_value > 0:
trend_text = f"{max_improve_country} showed the strongest improvement over this period"
else:
trend_text = "All countries show declining trends in this period"
if trend_text:
fig.add_annotation(
x=0.5,
y=-0.15,
xref="paper",
yref="paper",
text=f"<i>Trend Insight:</i> {trend_text}",
showarrow=False,
font=dict(
family="'Segoe UI', italic",
size=12,
color=COLORS["accent"]
),
align="center",
bgcolor=COLORS["accent-light"],
bordercolor=COLORS["accent"],
borderwidth=1,
borderpad=4
)
return fig
# Callback para generar el gráfico de clusters
@callback(
Output('clusters-graph', 'figure'),
[Input('domain-dropdown', 'value'),
Input('measure-dropdown', 'value'),
Input('year-dropdown', 'value')]
)
def update_clusters_graph(domain, measure, year):
if not domain or not measure or not year:
return go.Figure()
# Get clusters
cluster_df, cluster_labels = cluster_countries(oecd_df, domain, measure, year)
if len(cluster_df) == 0:
# Create an empty figure with a message
fig = go.Figure()
fig.update_layout(
title="Not enough data for clustering",
annotations=[
dict(
text="Insufficient data to create clusters for these parameters",
showarrow=False,
xref="paper",
yref="paper",
x=0.5,
y=0.5
)
]
)
return fig
# Create a color map
colors = [COLORS["primary"], COLORS["secondary"], COLORS["accent"]]
cluster_colors = {i: colors[i] for i in range(len(cluster_labels))}
# Create the scatter plot
fig = px.scatter(
cluster_df,
x='Country',
y='OBS_VALUE',
color='Cluster',
color_discrete_map={i: cluster_colors[i] for i in range(len(cluster_labels))},
title=f"Country Clusters for {measure} ({year})",
labels={'OBS_VALUE': measure, 'Cluster': 'Group', 'Country':''},
category_orders={"Cluster": sorted(cluster_df['Cluster'].unique())},
size=[12] * len(cluster_df)
)
# Add horizontal lines for cluster centers
for cluster, label in cluster_labels.items():
cluster_mean = cluster_df[cluster_df['Cluster'] == cluster]['OBS_VALUE'].mean()
fig.add_shape(
type="line",
x0=-0.5,
y0=cluster_mean,
x1=len(cluster_df['Country'].unique()) - 0.5,
y1=cluster_mean,
line=dict(
color=cluster_colors[cluster],
width=2,
dash="dash",
)
)
# Add annotation for cluster label
fig.add_annotation(
x=len(cluster_df['Country'].unique()) - 0.5,
y=cluster_mean,
text=label,
showarrow=False,
xshift=50,
font=dict(
color=cluster_colors[cluster],
size=12
),
bgcolor="rgba(255, 255, 255, 0.8)",
bordercolor=cluster_colors[cluster],
borderwidth=1,
borderpad=4
)
# Improve styling
fig.update_layout(
plot_bgcolor=COLORS["card-bg"],
paper_bgcolor=COLORS["card-bg"],
font_family="'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
font_color=COLORS["text-primary"],
showlegend=False,
margin=dict(l=40, r=120, t=60, b=120),
title={
'text': f"<b>Country Performance Groups</b> for {measure} ({year})",
'y':0.95,
'x':0.5,
'xanchor': 'center',
'yanchor': 'top',
'font': dict(size=18)
}
)
# Better x-axis with rotated labels
fig.update_xaxes(
tickangle=45,
tickmode='array',
tickvals=list(range(len(cluster_df['Country'].unique()))),
ticktext=cluster_df['Country'].unique()
)
# Add a storytelling annotation
fig.add_annotation(
x=0.5,
y=-0.4,
xref="paper",
yref="paper",
text=f"<i>Cluster Insight:</i> Countries are grouped by similar performance patterns",
showarrow=False,
font=dict(
family="'Segoe UI', italic",
size=12,
color=COLORS["secondary"]
),
align="center",
bgcolor=COLORS["secondary-light"],
bordercolor=COLORS["secondary"],
borderwidth=1,
borderpad=4
)
return fig
# Callback para generar el gráfico de predicciones
@callback(
Output('predictions-graph', 'figure'),
[Input('domain-dropdown', 'value'),
Input('measure-dropdown', 'value'),
Input('country-dropdown', 'value'),
Input('demographic-dropdown', 'value')]
)
def update_predictions_graph(domain, measure, countries, demographic_type):
if not domain or not measure or not countries or not demographic_type:
return go.Figure()
# We'll use 'Total' for demographic value for predictions
demographic_value = 'Total'
# Create figure
fig = go.Figure()
# Colors for countries
country_colors = [COLORS["primary"], COLORS["secondary"], COLORS["accent"],
"#D68C45", "#8E6C8A", "#4F94B8", "#97AC3D"]
# Add lines for each country
for i, country in enumerate(countries):
color = country_colors[i % len(country_colors)]
# Get historical data
historical_df = oecd_df[(oecd_df['Domain'] == domain) &
(oecd_df['Measure'] == measure) &
(oecd_df['Country'] == country) &
(oecd_df[demographic_type] == demographic_value)]
if len(historical_df) > 0:
# Add historical line
fig.add_trace(go.Scatter(
x=historical_df['Year'],
y=historical_df['OBS_VALUE'],
mode='lines+markers',
name=f"{country} (historical)",
line=dict(color=color),
marker=dict(size=12)
))
# Try to predict future values
future_years, predictions = predict_future_values(
oecd_df, domain, measure, country, demographic_type, demographic_value
)
if future_years is not None and len(future_years) > 0:
# Add prediction line
fig.add_trace(go.Scatter(
x=future_years,
y=predictions,
mode='lines',
name=f"{country} (predicted)",
line=dict(color=color, dash='dash'),
marker=dict(size=8)
))
# Add uncertainty area
# Simple approach: 5% margin above and below
fig.add_trace(go.Scatter(
x=np.concatenate([future_years, future_years[::-1]]),
y=np.concatenate([predictions * 1.05, (predictions * 0.95)[::-1]]),
fill='toself',
fillcolor=f"rgba({int(color[1:3], 16)}, {int(color[3:5], 16)}, {int(color[5:7], 16)}, 0.2)",
line=dict(color='rgba(0,0,0,0)'),
hoverinfo="skip",
showlegend=False
))
# Improve styling
fig.update_layout(
plot_bgcolor=COLORS["card-bg"],
paper_bgcolor=COLORS["card-bg"],
font_family="'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
font_color=COLORS["text-primary"],
margin=dict(l=40, r=40, t=60, b=80),
hoverlabel=dict(
bgcolor=COLORS["primary-light"],
font_size=12,
font_family="'Segoe UI', Roboto"
),
title={
'text': f"<b>Future Trends</b> for {measure}",
'y':0.95,
'x':0.5,
'xanchor': 'center',
'yanchor': 'top',
'font': dict(size=18)
}
)
# Add vertical line to separate historical and predicted data
if len(oecd_df) > 0:
max_year = max(oecd_df['Year'])
fig.add_vline(
x=max_year,
line_width=1,
line_dash="dot",
line_color=COLORS["text-secondary"],
annotation_text="Forecast starts",
annotation_position="top right"
)
# Add a storytelling annotation
fig.add_annotation(
x=0.5,
y=-0.15,
xref="paper",
yref="paper",
text=f"<i>Forecast Insight:</i> These projections extend current trends into the future",
showarrow=False,
font=dict(
family="'Segoe UI', italic",
size=8,
color=COLORS["accent"]
),
align="center",
bgcolor=COLORS["accent-light"],
bordercolor=COLORS["accent"],
borderwidth=1,
borderpad=4
)
return fig
# Callback para actualizar el texto interpretativo con estilo storytelling
@callback(
Output('interpretation-text', 'children'),
[Input('domain-dropdown', 'value'),
Input('measure-dropdown', 'value'),
Input('year-dropdown', 'value'),
Input('country-dropdown', 'value'),
Input('demographic-dropdown', 'value'),
Input('chart-tabs', 'active_tab')]
)
def update_interpretation_text(domain, measure, year, countries, demographic, active_tab):
if not domain or not measure:
return "Select parameters to see the story behind the numbers..."
# Get domain description for storytelling
domain_desc = domain_descriptions.get(domain, domain)
# Different interpretations based on active tab
if active_tab == "bar-tab":
return html.Div([
html.H5([html.I(className="fas fa-chart-bar me-2"), "Comparing Well-being Across Nations"]),
html.P([
"The chart above reveals how different countries compare on ",
html.Span(f"{measure}", className="fw-bold"),
", a key indicator in the ",
html.Span(f"{domain}", className="story-emphasis"),
" domain of well-being."
]),
html.P([
f"{domain_desc}"
]),
html.P([
"By examining differences across ",
html.Span(demographic.lower(), className="story-emphasis"),
" groups, we can uncover hidden patterns in well-being that might be missed in aggregate statistics.",
" These patterns often reflect deeper social structures, cultural values, and policy environments."
]),
html.P([
"What story does this data tell about societal priorities and challenges? ",
"Consider how historical contexts and policy choices might have shaped these outcomes."
], className="fst-italic text-muted mt-3")
])
elif active_tab == "time-tab":
return html.Div([
html.H5([html.I(className="fas fa-history me-2"), "The Evolution of Well-being"]),
html.P([
"This timeline shows how ",
html.Span(f"{measure}", className="fw-bold"),
" has evolved over time, revealing progress, setbacks, and persistent challenges in the ",
html.Span(f"{domain.lower()}", className="story-emphasis"),
" domain."
]),
html.P([
"Trajectories often reflect major policy shifts, economic cycles, or social transformations. ",
"Diverging paths between countries can highlight different approaches to similar challenges."
]),
html.P([
"Look for pivotal moments where trends change direction—these often mark important policy ",
"interventions or external shocks that reshape well-being outcomes."
]),
html.P([
"What future directions do these trajectories suggest? Which approaches appear most sustainable or equitable?"
], className="fst-italic text-muted mt-3")
])
elif active_tab == "clusters-tab":
return html.Div([
html.H5([html.I(className="fas fa-object-group me-2"), "Patterns Across Nations"]),
html.P([
"This analysis groups countries into clusters based on their performance in ",
html.Span(f"{measure}", className="fw-bold"),
", revealing natural groupings in the data."
]),
html.P([
"Countries within the same cluster often share similar historical contexts, policy approaches, ",
"or socioeconomic conditions that contribute to comparable outcomes in this aspect of ",
html.Span(f"{domain.lower()}", className="story-emphasis"),
"."
]),
html.P([
"These patterns invite deeper investigation: What common characteristics or policies might explain ",
"why certain countries cluster together? What can lower-performing countries learn from those with stronger outcomes?"
]),
html.P([
"Consider these clusters as starting points for more nuanced comparative analysis, rather than definitive groupings."
], className="fst-italic text-muted mt-3")
])
elif active_tab == "predictions-tab":
return html.Div([
html.H5([html.I(className="fas fa-crystal-ball me-2"), "Glimpsing Future Possibilities"]),
html.P([
"These projections extend current trends in ",
html.Span(f"{measure}", className="fw-bold"),
" to suggest possible future trajectories, based on historical patterns in the ",
html.Span(f"{domain.lower()}", className="story-emphasis"),
" domain."
]),
html.P([
"The shaded areas represent uncertainty—reminder that the future is not predetermined. ",
"Policy interventions, social changes, or external disruptions could alter these trajectories."
]),
html.P([
"Countries with diverging projections suggest different levels of sustainability in current approaches. ",
"Convergence might indicate that different paths ultimately lead to similar outcomes over time."
]),
html.P([
"How might these projections inform current policy priorities? What interventions could help bend concerning trends toward more positive outcomes?"
], className="fst-italic text-muted mt-3")
])
else:
return "Explore the data to uncover the story behind the numbers..."