File size: 8,925 Bytes
76aee8e 2669977 081d5d1 76aee8e 572e3c3 76aee8e 081d5d1 76aee8e 081d5d1 76aee8e 572e3c3 081d5d1 572e3c3 081d5d1 76aee8e 081d5d1 76aee8e 081d5d1 76aee8e 081d5d1 76aee8e 081d5d1 3dd0e03 081d5d1 572e3c3 081d5d1 76aee8e 081d5d1 76aee8e 081d5d1 76aee8e 572e3c3 76aee8e 572e3c3 76aee8e 572e3c3 76aee8e db3a4d1 76aee8e 572e3c3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 | import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from dash import Dash, dcc, html, Input, Output, State, ctx
import dash_daq as daq
import numpy as np
import dash_bootstrap_components as dbc
# 1. Data Loading & Preprocessing
df_global = pd.read_csv("merged_global.csv")
df_hemi = pd.read_csv("hemispheric_merged.csv")
# Merge by Year and Month
df = pd.merge(df_global, df_hemi, on=["year", "month"], suffixes=("", "_hemi"))
# For the seaosnal analysis categorizing the months
def get_season(month):
return {
12: "DJF", 1: "DJF", 2: "DJF",
3: "MAM", 4: "MAM", 5: "MAM",
6: "JJA", 7: "JJA", 8: "JJA",
9: "SON", 10: "SON", 11: "SON"
}[month]
df["Season"] = df["month"].apply(get_season)
# 2. App Initialization
app = Dash(__name__)
app.title = "Correlation & Insight Explorer"
# Define the variables for the dropdowns
def get_variables(scope):
if scope == "global":
return {
"co2_anomaly": "COโ Anomaly",
"land_ocean_anomaly": "Global Land+Ocean Temp Anomaly",
"land_anomaly": "Global Land Temp Anomaly",
"msl_mm": "Sea Level Change"
}
elif scope == "nh":
return {
"north_co2_anomaly": "NH COโ Anomaly",
"north_land_ocean_anomaly": "NH Land+Ocean Temp Anomaly",
"north_land_anomaly": "NH Land Temp Anomaly",
"msl_mm_north": "NH Sea Level Change"
}
elif scope == "sh":
return {
"south_co2_anomaly": "SH COโ Anomaly",
"south_land_ocean_anomaly": "SH Land+Ocean Temp Anomaly",
"south_land_anomaly": "SH Land Temp Anomaly",
"msl_mm_south": "SH Sea Level Change"
}
# 3. App Layout
app = Dash(__name__, external_stylesheets=[dbc.themes.FLATLY])
app.title = "Correlation & Insight Explorer"
app.layout = dbc.Container([
dbc.Row([
dbc.Col(html.H2("Correlation & Insight Explorer", className="text-center"), width=12)
], className="my-3"),
dbc.Row([
dbc.Col([
html.Label("Scope"),
dcc.RadioItems(id="scope-selector", options=[
{"label": "๐ Global", "value": "global"},
{"label": "๐ Northern Hemisphere", "value": "nh"},
{"label": "๐ Southern Hemisphere", "value": "sh"}
], value="global", labelStyle={"display": "block"})
], md=6),
dbc.Col([
html.Label("Theme"),
daq.ToggleSwitch(id='theme-toggle', label=['Light', 'Dark'], value=False)
], md=6)
], className="mb-3"),
dbc.Row([
dbc.Col([
html.Label("X-axis Variable"),
html.P("Select the variable for the X-axis"),
dcc.Dropdown(id='x-axis-dropdown', placeholder="Choose a variable for X-axis")
], md=6),
dbc.Col([
html.Label("Y-axis Variable"),
html.P("Select the variable for the Y-axis"),
dcc.Dropdown(id='y-axis-dropdown', placeholder="Choose a variable for Y-axis")
], md=6)
], className="mb-3"),
dbc.Row([
dbc.Col([
html.Label("Year Range"),
dcc.RangeSlider(
id='year-slider',
min=df['year'].min(), max=df['year'].max(),
value=[df['year'].min(), df['year'].max()],
marks={str(year): str(year) for year in range(df['year'].min(), df['year'].max()+1, 5)},
step=1
),
html.Label("View Mode", style={'marginTop': '10px'}),
dcc.RadioItems(
id='view-mode',
options=[
{"label": "Monthly", "value": "Monthly"},
{"label": "Seasonal", "value": "Seasonal"}
],
value="Monthly",
labelStyle={"display": "inline-block", "margin-right": "10px"}
)
], md=12)
], className="mb-4"),
dbc.Card([
dbc.CardHeader("๐ What Youโre Seeing โ Climate Insights"),
dbc.CardBody([
html.P("This interactive tool allows you to explore the statistical relationships between climate indicators:"),
html.Ul([
html.Li("๐ฑ Human-induced COโ emissions heat the planet โก๏ธ"),
html.Li("๐ก๏ธ Rising COโ leads to higher land and ocean temperatures โก๏ธ"),
html.Li("๐ Warmer climates cause sea level rise through ice melt and ocean expansion.")
]),
html.P("Switch views (Global, Northern, Southern Hemisphere) and select indicators and years to compare."),
html.P("The scatter plot shows how the selected variables change together, with a regression trendline and Rยฒ value."),
html.P("Pearson's r (shown in the heatmap and above the scatter) helps you evaluate correlation strength."),
html.P("The correlation heatmap reveals how all indicators relate within your selected range.")
])
], className="mb-4"),
html.Div(id='correlation-note', style={'padding': '10px', 'fontSize': '16px'}),
dcc.Graph(id='scatter-plot'),
html.H4("Correlation Matrix (Pearson)", className="text-center mt-4"),
dcc.Graph(id='correlation-heatmap')
], fluid=True)
# 4. Callbacks
@app.callback(
Output('x-axis-dropdown', 'options'),
Output('y-axis-dropdown', 'options'),
Output('x-axis-dropdown', 'value'),
Output('y-axis-dropdown', 'value'),
Input('scope-selector', 'value') )
def update_variable_options(scope):
vars = get_variables(scope)
options = [{'label': v, 'value': k} for k, v in vars.items()]
return options, options, list(vars.keys())[0], list(vars.keys())[1]
@app.callback(
Output('scatter-plot', 'figure'),
Output('correlation-heatmap', 'figure'),
Output('correlation-note', 'children'),
Input('x-axis-dropdown', 'value'),
Input('y-axis-dropdown', 'value'),
Input('year-slider', 'value'),
Input('view-mode', 'value'),
Input('scope-selector', 'value'),
Input('theme-toggle', 'value')
)
def update_visuals(x_var, y_var, year_range,view_mode, scope, dark_mode):
vars_dict = get_variables(scope)
dff = df[(df["year"] >= year_range[0]) & (df["year"] <= year_range[1])]
"""
Updating both charts based on user inputs
Supports theme switching and monthly/seasonal toggling.
"""
# If the view mode switched one the seasonal the month columns are not needed
if view_mode == "Seasonal":
dff = dff.groupby(['year', 'Season']).mean(numeric_only=True).reset_index()
else:
dff = dff.copy()
r = dff[[x_var, y_var]].corr().iloc[0, 1]
strength = "No correlation"
if abs(r) > 0.8:
strength = "๐ Very strong correlation"
elif abs(r) > 0.6:
strength = "๐ Strong correlation"
elif abs(r) > 0.4:
strength = "๐ Moderate correlation"
elif abs(r) > 0.2:
strength = "๐ Weak correlation"
elif abs(r) > 0:
strength = "๐ Very weak correlation"
corr_sentence = f"{strength} detected (r = {r:.2f})"
# Scatter Plot with Regression
fig = px.scatter(
dff, x=x_var, y=y_var, trendline="ols",
title=f"{vars_dict[x_var]} vs {vars_dict[y_var]}",
labels={x_var: vars_dict[x_var], y_var: vars_dict[y_var]},
template="plotly_dark" if dark_mode else "plotly_white"
)
fig.update_traces(
hovertemplate=f"<b>Year</b>: %{{customdata[0]}}<br><b>Month/Season</b>: %{{customdata[1]}}<br><b>{vars_dict[x_var]}</b>: %{{x:.3f}}<br><b>{vars_dict[y_var]}</b>: %{{y:.3f}}",
customdata=dff[["year", "Season"]] if view_mode == "Seasonal" else dff[["year", "month"]]
)
# Add Rยฒ if OLS exists
try:
results = px.get_trendline_results(fig)
r_squared = results.iloc[0]["px_fit_results"].rsquared
fig.add_annotation(
xref="paper", yref="paper",
x=0.95, y=0.05,
text=f"Rยฒ = {r_squared:.2f}",
showarrow=False,
font=dict(size=14, color="white" if dark_mode else "black")
)
except:
pass
corr = dff[list(vars_dict.keys())].corr().round(2)
heatmap = go.Figure(data=go.Heatmap(
z=corr.values,
x=list(vars_dict.values()),
y=list(vars_dict.values()),
colorscale='Cividis',
zmin=-1, zmax=1,
colorbar=dict(title="Pearson r")
))
heatmap.update_layout(template="plotly_dark" if dark_mode else "plotly_white")
return fig, heatmap, corr_sentence
server = app.server # Required for gunicorn
# 5. Run app
if __name__ == '__main__':
app.run_server(debug=True, host='0.0.0.0', port=7860)
dbc.Row([
dbc.Col(html.Footer("Created by Irem R. as part of Bachelor Thesis at Riga Technical University โ 2025", className="text-center text-muted"), width=12)
], className="mt-4")
|