Spaces:
Running
Running
File size: 9,473 Bytes
c47a6e2 | 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 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | """
dashboard_helpers.py — Map-building and chart functions used by app.py
"""
import numpy as np
import pandas as pd
import geopandas as gpd
import leafmap
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.colors as mcolors
def _classify_terciles(series):
out = pd.Series(-1, index=series.index, dtype=int)
mask = series.notna()
if mask.sum() < 3:
return out
labels = pd.qcut(series[mask], q=3, labels=[0, 1, 2], duplicates="drop")
out[mask] = labels.astype(int)
return out
# Bivariate palette
# X axis = environmental variable (NDVI or TES): color (red=low, yellow=mid, green=high)
# Y axis = demographic variable: shade (dark=high % community of concern, light=low % community of concern)
BIVARIATE_COLORS = [
"#8B0000",
"#B8860B",
"#1B5E20",
"#CD5C5C",
"#DAA520",
"#4CAF50",
"#F4CCCC",
"#FFF9C4",
"#C8E6C9",
]
CMAP_NAME = "bivariate_9"
# Bivariate choropleth map
def build_bivariate_map(con, x_col, x_label, y_col, y_label):
df = con.sql(f"""
SELECT GEOID, geometry_wkt, {x_col}, {y_col}
FROM block_groups
WHERE total_pop > 0
AND {x_col} IS NOT NULL
AND {y_col} IS NOT NULL
""").df()
gdf = gpd.GeoDataFrame(
df,
geometry=gpd.GeoSeries.from_wkt(df["geometry_wkt"]),
crs="EPSG:4269"
).drop(columns="geometry_wkt")
gdf["x_class"] = _classify_terciles(gdf[x_col])
# For minority %, invert so that high minority = dark
if y_col == "pct_minority":
gdf["y_class"] = _classify_terciles(gdf[y_col]).map({2: 0, 1: 1, 0: 2, -1: -1})
else:
gdf["y_class"] = _classify_terciles(gdf[y_col])
gdf["bv_class"] = gdf.apply(
lambda r: int(r["y_class"]) * 3 + int(r["x_class"])
if r["x_class"] >= 0 and r["y_class"] >= 0 else float("nan"),
axis=1
)
gdf_valid = gdf[gdf["bv_class"].notna()].copy()
gdf_valid["bv_class"] = gdf_valid["bv_class"].astype(float)
cmap = mcolors.ListedColormap(BIVARIATE_COLORS, name=CMAP_NAME)
try:
matplotlib.colormaps.register(cmap, name=CMAP_NAME)
except Exception:
pass
gdf_valid["hex_color"] = gdf_valid["bv_class"].apply(
lambda c: BIVARIATE_COLORS[int(c)] if not np.isnan(c) else "#cccccc"
)
# Save to a temp file and load via leafmap
import tempfile, os
tmp = tempfile.NamedTemporaryFile(suffix=".geojson", delete=False)
tmp.close()
gdf_valid[["geometry", "bv_class", "hex_color", "GEOID"]].to_file(tmp.name, driver="GeoJSON")
import folium
m = folium.Map(location=[33.45, -112.07], zoom_start=10,
tiles="CartoDB dark_matter")
for _, row in gdf_valid.iterrows():
folium.GeoJson(
row.geometry.__geo_interface__,
style_function=lambda f, c=row["hex_color"]: {
"fillColor": c,
"fillOpacity": 0.75,
"color": "#444",
"weight": 0.4,
}
).add_to(m)
return m
# Bivariate legend
def build_bivariate_legend(x_label, y_label, y_col):
palette = [
["#8B0000", "#B8860B", "#1B5E20"], # low Y: dark shades
["#CD5C5C", "#DAA520", "#4CAF50"], # mid Y: medium shades
["#F4CCCC", "#FFF9C4", "#C8E6C9"], # high Y: light shades
]
fig, ax = plt.subplots(figsize=(3.5, 3.5), facecolor="#1a1a2e")
ax.set_facecolor("#1a1a2e")
for row in range(3):
for col in range(3):
rect = mpatches.FancyBboxPatch(
(col, row), 1, 1,
boxstyle="square,pad=0",
facecolor=palette[row][col],
edgecolor="#333", linewidth=0.5
)
ax.add_patch(rect)
ax.set_xlim(0, 3)
ax.set_ylim(0, 3)
ax.set_xticks([0.5, 1.5, 2.5])
ax.set_xticklabels(["Low", "Med", "High"], color="#c9d1d9", fontsize=8)
ax.set_yticks([0.5, 1.5, 2.5])
if y_col == "pct_minority":
ax.set_yticklabels(["High", "Med", "Low"], color="#c9d1d9", fontsize=8)
else:
ax.set_yticklabels(["Low", "Med", "High"], color="#c9d1d9", fontsize=8)
ax.set_xlabel(x_label, color="#c9d1d9", fontsize=9, labelpad=8)
ax.set_ylabel(y_label, color="#c9d1d9", fontsize=9, labelpad=8)
ax.tick_params(length=0)
for spine in ax.spines.values():
spine.set_visible(False)
fig.subplots_adjust(left=0.22, bottom=0.18, right=0.95, top=0.95)
return fig
# Summary stats table
def build_summary_stats(con, x_col, y_col):
df = con.sql(f"""
SELECT {x_col}, {y_col}, tree_equity_score, ndvi_mean, total_pop
FROM block_groups
WHERE total_pop > 0
AND {x_col} IS NOT NULL
AND {y_col} IS NOT NULL
""").df()
df["x_tercile"] = _classify_terciles(df[x_col]).map(
{-1: "No data", 0: f"Low", 1: f"Mid", 2: f"High"}
)
summary = (
df.groupby("x_tercile")
.agg(
Block_Groups=(x_col, "count"),
**{f"Avg_{x_col}": (x_col, lambda x: round(x.mean(), 2))},
**{f"Avg_{y_col}": (y_col, lambda x: round(x.mean(), 1))},
Avg_TES=("tree_equity_score", lambda x: round(x.mean(), 1) if x.notna().any() else np.nan),
Avg_NDVI=("ndvi_mean", lambda x: round(x.mean(), 3) if x.notna().any() else np.nan),
)
.reindex(["Low", "Mid", "High"])
.reset_index()
.rename(columns={"x_tercile": "Group"})
)
styled = summary.style.background_gradient(
cmap="RdYlGn", subset=[f"Avg_{x_col}"]
).hide(axis="index")
return styled
# Tree-need bar chart
def build_need_chart(con, y_col):
df = con.sql(f"""
SELECT GEOID, ndvi_mean, tree_equity_score, {y_col}
FROM block_groups
WHERE ndvi_mean IS NOT NULL AND tree_equity_score IS NOT NULL
AND {y_col} IS NOT NULL AND total_pop > 0
""").df()
if df.empty:
fig, ax = plt.subplots(facecolor="#161b22")
ax.text(0.5, 0.5, "No data yet", ha="center", va="center", color="#8b949e")
return fig
def minmax(s):
mn, mx = s.min(), s.max()
return (s - mn) / (mx - mn) if mx > mn else s * 0
df["ndvi_norm"] = minmax(df["ndvi_mean"])
df["tes_norm"] = minmax(df["tree_equity_score"])
df["need"] = (1 - df["ndvi_norm"]) * 0.5 + (1 - df["tes_norm"]) * 0.5
if y_col == "pct_minority":
df["shade_norm"] = minmax(df[y_col]) # high = darker
else:
df["shade_norm"] = 1 - minmax(df[y_col]) # low income = darker
top15 = df.nlargest(15, "need").reset_index(drop=True)
labels = [str(g)[-6:] for g in top15["GEOID"]]
x = np.arange(len(top15))
fig, ax = plt.subplots(figsize=(10, 3.2), facecolor="#161b22")
ax.set_facecolor("#161b22")
for i, row in top15.iterrows():
alpha = 0.3 + 0.7 * row["shade_norm"]
ax.bar(i, row["need"], color="#e05c5c", alpha=alpha, width=0.6)
# Shade legend
y_label = "% Minority" if y_col == "pct_minority" else "Median Income"
from matplotlib.patches import Patch
legend_elements = [
Patch(facecolor="#e05c5c", alpha=1.0,
label=f"High concern ({('high' if y_col == 'pct_minority' else 'low')} {y_label})"),
Patch(facecolor="#e05c5c", alpha=0.3,
label=f"Lower concern ({('low' if y_col == 'pct_minority' else 'high')} {y_label})"),
]
ax.set_xticks(x)
ax.set_xticklabels(labels, rotation=45, ha="right", color="#8b949e", fontsize=8)
ax.set_ylabel("Tree Need Score", color="#8b949e", fontsize=8)
ax.set_title("Top 15 Block Groups by Tree Program Need (GEOID suffix)",
color="#c9d1d9", fontsize=9, pad=6)
ax.tick_params(colors="#8b949e", labelsize=8)
for sp in ax.spines.values():
sp.set_color("#30363d")
ax.legend(handles=legend_elements, frameon=False,
labelcolor="#8b949e", fontsize=8, loc="upper right")
fig.tight_layout(pad=0.5)
return fig
def build_need_map(con, y_col):
df = con.sql(f"""
SELECT GEOID, geometry_wkt, ndvi_mean, tree_equity_score, {y_col}
FROM block_groups
WHERE ndvi_mean IS NOT NULL AND tree_equity_score IS NOT NULL
AND {y_col} IS NOT NULL AND total_pop > 0
""").df()
def minmax(s):
mn, mx = s.min(), s.max()
return (s - mn) / (mx - mn) if mx > mn else s * 0
df["ndvi_norm"] = minmax(df["ndvi_mean"])
df["tes_norm"] = minmax(df["tree_equity_score"])
df["need"] = (1 - df["ndvi_norm"]) * 0.5 + (1 - df["tes_norm"]) * 0.5
top15_geoids = set(df.nlargest(15, "need")["GEOID"].tolist())
gdf = gpd.GeoDataFrame(
df,
geometry=gpd.GeoSeries.from_wkt(df["geometry_wkt"]),
crs="EPSG:4269"
).drop(columns="geometry_wkt")
import folium
m = folium.Map(location=[33.45, -112.07], zoom_start=9,
tiles="CartoDB dark_matter")
for _, row in gdf.iterrows():
is_top15 = row["GEOID"] in top15_geoids
folium.GeoJson(
row.geometry.__geo_interface__,
style_function=lambda f, top=is_top15: {
"fillColor": "#e05c5c" if top else "#444444",
"fillOpacity": 0.85 if top else 0.3,
"color": "#e05c5c" if top else "#333333",
"weight": 1.5 if top else 0.3,
}
).add_to(m)
return m
|