Spaces:
Sleeping
Sleeping
HsiehMinChieh Claude Opus 5.5 commited on
Commit ·
527e290
1
Parent(s): 8528213
feat: 地圖改海面底色與分層框線;鄉鎮圖加「縣市+相鄰縣市」範圍
Browse files- 底圖:互動圖與靜態圖(PNG、GIF、PPTX)都加淡藍海面底色
- 框線:縣市界深灰;鄉鎮界淺灰細線,再疊一層深灰縣市界(單一縣市與相鄰縣市範圍也有,只畫圖上有的縣市)
- 範圍:主地圖新增鄉鎮範圍選單(鄉鎮層級才顯示),手動填寫的範圍也多了「某縣市+相鄰縣市」,方便看跨縣市的外溢、擴散
- 排名圖卡維持白底,只把白色界線改成深灰
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
566 unmodified lines56756856957057157294 unmodified lines66766866967067167267367467595 unmodified lines7717727737747757767775 unmodified lines7837847857867877887897 unmodified lines7977987998008018028034 unmodified lines808809810811812813814815816817818819820121 unmodified lines9429439449459469479489499509518 unmodified lines96096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099116 unmodified lines10081009101010111012101310141015145 unmodified lines1161116211631164116511661167116828 unmodified lines119711981199120012011202120375 unmodified lines127912801281128212831284128522 unmodified lines1308130913101311131213131314131513161317131813191320132113221323132413253 unmodified lines1329133013311332133313341335112 unmodified lines14481449145014511452145314541455145614571458145910 unmodified lines14701471147214731474147514761477147814791480148144 unmodified lines152615271528152915301531153215331534153515361537153815391540451 unmodified lines1992199319941995199619971998666 unmodified lines2665266626672668266926708 unmodified lines2679268026812682268326842685137 unmodified lines2823282428252826282728282829566 unmodified linesAGG_FUNCS = {"加總": "sum", "平均": "mean", "最大值": "max"}CLASS_MODES = ["連續", "分位數 (5 級)", "等距 (5 級)"]NO_DATA_COLOR = "#d1d5db"NO_DATA_LABEL = "無資料"def _scheme_key(color_scheme) -> str:94 unmodified linescolors = px.colors.sample_colorscale(COLOR_SCALES[scheme], pos)return dict(zip(labels, (_to_hex(c) for c in colors)))def _style_map_layout(fig, title: str, bottom_legend: bool = False):fig.update_geos(fitbounds="locations", visible=False)fig.update_traces(marker_line_width=0.4, marker_line_color="white", selector=dict(type="choropleth"))layout = dict(margin={"r": 0, "t": 50, "l": 0, "b": 40},height=750, autosize=True,95 unmodified linesshowscale=False, text=missing['name'],hovertemplate=f"%{{text}}<br>{NO_DATA_LABEL}<extra></extra>"))_style_map_layout(fig, title)else:labels, label_series = binnedmerged = merged.assign(分級=label_series)5 unmodified linescolor_discrete_map=palette, category_orders={'分級': order},projection="mercator", hover_name='name', hover_data={**hover_data, '分級': False})_style_map_layout(fig, title, bottom_legend=True)return add_region_picker(fig, merged, stats=[(value_col, merged[value_col])])def build_static_map(merged, value_col, title, scheme="紅色系", mode="連續", figsize=(12, 12),7 unmodified linesbinned = classify(merged[value_col], mode, edges=edges)if binned is None:vmin, vmax = vrange if vrange else (None, None)merged.plot(column=value_col, cmap=MPL_CMAPS[scheme], linewidth=0.5, ax=ax, edgecolor='0.5',vmin=vmin, vmax=vmax, legend=True, legend_kwds={'shrink': 0.6, 'pad': cbar_pad},missing_kwds={'color': NO_DATA_COLOR, 'label': NO_DATA_LABEL})else:4 unmodified linesfor lab in labels + [NO_DATA_LABEL]:sub = merged[label_series == lab]if lab == NO_DATA_LABEL and sub.empty: continueif not sub.empty: sub.plot(ax=ax, color=palette[lab], linewidth=0.5, edgecolor='0.5')handles.append(Patch(facecolor=palette[lab], edgecolor='0.5', label=lab)) # 空級距也列在圖例,各幀圖例一致ax.legend(handles=handles, title=value_col, loc='lower right', fontsize=legend_size,title_fontsize=legend_size + 1)font_kw = {'fontproperties': CUSTOM_FONT_PROP} if CUSTOM_FONT_PROP else {}ax.set_title(title, size=title_size, **font_kw)ax.set_axis_off()return fig# === 統計摘要函式 (白底深字版) ===121 unmodified linesgeojson=geo_json, locations=merged.index, z=z, colorscale=scale, name=name,text=merged['name'], hovertemplate="%{text}<br>" + name + ": %{z:,.0f}<extra></extra>",showscale=True, colorbar=dict(orientation="h", x=x, y=0, len=0.4, thickness=10, title=name),geo="geo" if idx == 1 else "geo2", marker_line_width=0.4, marker_line_color="white"), row=1, col=idx)geo_common = dict(visible=False, projection_type="mercator", fitbounds="locations")fig.update_layout(geo=dict(**geo_common, domain=dict(x=[0, 0.48], y=[0, 1])),geo2=dict(**geo_common, domain=dict(x=[0.52, 1], y=[0, 1])),8 unmodified linesISLAND_COUNTIES = ('金門縣', '連江縣', '澎湖縣')def _map_frame(df, col, time, agg_method, map_level_state, show_islands):"""彙整指標並合併到地圖;關閉離島時移除金門/連江/澎湖,讓本島可以放大"""target_gdf = _require_map(map_level_state)if not show_islands:target_gdf = target_gdf[~target_gdf['name'].str.startswith(ISLAND_COUNTIES)]return merge_geo(target_gdf, aggregate_by_region(df, col, time, agg_method))def generate_map(df, col, time, agg_method, color_scheme, class_mode, show_islands, map_level_state, all_cols):_require_regions(df)col = _resolve_col(col, all_cols)try:merged = _map_frame(df, col, time, agg_method, map_level_state, show_islands)fig = build_choropleth(merged, col, f"🗺️ {col} - 地理分布圖({_period_label(time)})",scheme=_scheme_key(color_scheme), mode=class_mode)return fig, gr.Tabs(selected="tab_map")except Exception as e:raise gr.Error(f"繪圖失敗: {e}")def export_static_map(df, col, time, agg_method, color_scheme, class_mode, show_islands, map_level_state, all_cols):_require_regions(df)col = _resolve_col(col, all_cols)try:merged = _map_frame(df, col, time, agg_method, map_level_state, show_islands)fig = build_static_map(merged, col, f"{col} - 地圖 ({_period_label(time)})",scheme=_scheme_key(color_scheme), mode=class_mode, figsize=(15, 15))path = _named_path(_map_stem(col, time, map_level_state), ".png")fig.savefig(path, dpi=200, bbox_inches='tight', facecolor='white')16 unmodified linesexcept Exception:return gr.update()def export_html_map(df, col, time, agg_method, color_scheme, class_mode, show_islands, map_level_state, all_cols):fig, _ = generate_map(df, col, time, agg_method, color_scheme, class_mode, show_islands, map_level_state, all_cols)path = _named_path(_map_stem(_resolve_col(col, all_cols), time, map_level_state, "(互動)"), ".html")fig.write_html(path, include_plotlyjs="cdn")return gr.update(value=path, visible=True)145 unmodified lines"宜蘭縣", "花蓮縣", "臺東縣", "澎湖縣", "金門縣", "連江縣"]MANUAL_LEVELS = ["縣市", "鄉鎮市區"]MANUAL_NATIONAL = "全國"MANUAL_LABEL_MODES = ["名稱 + 內容", "僅內容", "僅名稱", "不顯示標籤"]MANUAL_COLORS = ["紅色系 🔴", "藍色系 🔵", "綠色系 🟢", "熱力圖 🔥"]MANUAL_COL_NAME, MANUAL_COL_CONTENT = "名稱", "填寫內容"28 unmodified lines"""目前表格要列出的名稱:縣市層級=22 縣市;鄉鎮層級=全國或某縣市底下的鄉鎮市區"""if level != "鄉鎮市區": return list(DEFAULT_COUNTIES)gdf = _town_gdf()if scope in DEFAULT_COUNTIES: gdf = gdf[gdf['縣市'] == scope]order = {c: i for i, c in enumerate(DEFAULT_COUNTIES)}sort_cols = ['town_id'] if 'town_id' in gdf.columns else ['name']gdf = gdf.assign(_o=gdf['縣市'].map(order)).sort_values(['_o'] + sort_cols)75 unmodified linesn = normalize_name(raw)if n in names: return nif level == "鄉鎮市區":if scope in DEFAULT_COUNTIES and scope + n in names: return scope + ncands = short.get(n, [])if len(cands) == 1: return cands[0] # 全國範圍下,名稱唯一的鄉鎮可以只寫短名return None22 unmodified lines# --- 資料合併與繪圖 ---_COUNTY_OUTLINE_CACHE: Dict[str, Tuple[list, list]] = {}def county_outline_lines() -> Tuple[list, list]:"""全部縣市界線的座標(以 None 分段),疊在全國鄉鎮圖上,才看得出縣市邊界"""if "xy" not in _COUNTY_OUTLINE_CACHE:lon, lat = [], []for geom in _require_map("county").geometry.boundary:for line in getattr(geom, "geoms", [geom]):xs, ys = line.xylon += list(xs) + [None]; lat += list(ys) + [None]_COUNTY_OUTLINE_CACHE["xy"] = (lon, lat)return _COUNTY_OUTLINE_CACHE["xy"]def _manual_frame(input_df, level, scope, show_islands=True, numeric=None):"""3 unmodified lines"""if level == "鄉鎮市區":target = _town_gdf()if scope in DEFAULT_COUNTIES: target = target[target['縣市'] == scope]else:target = _require_map("county")if input_df is None or len(input_df) == 0: raise gr.Error("請至少填寫一個項目的內容")112 unmodified lines"""有填標題就用標題;沒填就用「縣市統計圖」「新北市鄉鎮市區統計圖」"""if (title or "").strip(): return title.strip()if level != "鄉鎮市區": return "縣市統計圖"return "全國鄉鎮市區統計圖" if scope not in DEFAULT_COUNTIES else f"{scope}鄉鎮市區統計圖"def _manual_title(title: str, level: str, scope: str) -> str:if (title or "").strip(): return title.strip()if level != "鄉鎮市區": return "臺灣各縣市"return "全國各鄉鎮市區" if scope not in DEFAULT_COUNTIES else f"{scope}各鄉鎮市區"def generate_manual_distribution_map(input_df, level, scope, title, color_scheme, label_mode, label_size, show_islands):merged, is_numeric = _manual_frame(input_df, level, scope, show_islands)10 unmodified linescategory_orders={"類別": cats + ([UNFILLED_LABEL] if (~merged["filled"]).any() else [])},projection="mercator", hover_name="name", hover_data={"類別": False})_style_map_layout(fig, title, bottom_legend=True)if level == "鄉鎮市區" and scope not in DEFAULT_COUNTIES: # 全國鄉鎮圖疊上縣市界lon, lat = county_outline_lines()fig.add_trace(go.Scattergeo(lon=lon, lat=lat, mode="lines", hoverinfo="skip", showlegend=False,line=dict(color="#374151", width=0.8)))filled = merged[merged["filled"]]if label_mode != "不顯示標籤" and not filled.empty:44 unmodified linescats, palette = _category_palette(merged, cats)for cat in cats + [UNFILLED_LABEL]:sub = merged[merged["類別"] == cat]if not sub.empty: sub.plot(ax=ax, color=palette[cat], edgecolor="white", linewidth=0.5)handles = [Patch(facecolor=palette[c], edgecolor="0.5", label=c) for c in cats]if handles: ax.legend(handles=handles, loc="lower right", fontsize=12)font_kw = {"fontproperties": CUSTOM_FONT_PROP} if CUSTOM_FONT_PROP else {}ax.set_title(title, size=24, **font_kw)ax.set_axis_off()if level == "鄉鎮市區" and scope not in DEFAULT_COUNTIES:_require_map("county").boundary.plot(ax=ax, color="#374151", linewidth=0.7)ax.apply_aspect()fs = int(label_size) * 0.85451 unmodified linesmap_ax = fig.add_axes([map_x0 / W, map_y0 / H, (map_x1 - map_x0) / W, (map_y1 - map_y0) / H])for cls in ("none", "other", "top", "bottom"):sub = main[main["_class"] == cls]if not sub.empty: sub.plot(ax=map_ax, color=color_of[cls], edgecolor="white", linewidth=0.8)bx0, by0, bx1, by1 = main.total_boundsmap_ax.set_xlim(bx0 - 0.02, bx1 + 0.02); map_ax.set_ylim(by0 - 0.02, by1 + 0.02)map_ax.set_axis_off()666 unmodified lines)class_mode = gr.Dropdown(CLASS_MODES, label="分級方式", value=CLASS_MODES[0])show_islands = gr.Checkbox(label="顯示離島(金門、連江、澎湖)— 關閉後本島會放大", value=True)with gr.Row():btn_map = gr.Button("🔄 更新地圖", variant="primary", scale=2)btn_export_map = gr.Button("💾 匯出 PNG", variant="secondary")8 unmodified lineswith gr.Column(scale=1, min_width=300):with gr.Row():manual_level = gr.Radio(MANUAL_LEVELS, label="層級", value=MANUAL_LEVELS[0])manual_scope = gr.Dropdown([MANUAL_NATIONAL] + DEFAULT_COUNTIES, label="鄉鎮範圍(全國 或 單一縣市)",value="臺北市", visible=False)manual_input_df = gr.Dataframe(value=manual_table("縣市", MANUAL_NATIONAL, {}),137 unmodified lines}""")map_inputs = [current_df, col_selector, time_selector, agg_method, color_scheme, class_mode,show_islands, map_level_state, all_numeric_cols_state]file_input.change(fn=process_uploaded_file, inputs=file_input,566 unmodified lines56756856957057157257357457557657757894 unmodified lines67367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770895 unmodified lines8048058068078088098105 unmodified lines8168178188198208218228237 unmodified lines8318328338348358368378384 unmodified lines843844845846847848849850851852853854855856121 unmodified lines9789799809819829839849859869879888 unmodified lines9979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103416 unmodified lines10511052105310541055105610571058145 unmodified lines1204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123528 unmodified lines126412651266126712681269127075 unmodified lines1346134713481349135013511352135322 unmodified lines137613771378137913801381138213831384138513861387138813891390139113921393139413953 unmodified lines1399140014011402140314041405112 unmodified lines15181519152015211522152315241525152615271528152910 unmodified lines1540154115421543154415451546154744 unmodified lines1592159315941595159615971598159916001601160216031604451 unmodified lines2056205720582059206020612062666 unmodified lines272927302731273227332734273527368 unmodified lines2745274627472748274927502751137 unmodified lines288928902891289228932894289528962897566 unmodified linesAGG_FUNCS = {"加總": "sum", "平均": "mean", "最大值": "max"}CLASS_MODES = ["連續", "分位數 (5 級)", "等距 (5 級)"]NO_DATA_COLOR = "#d1d5db"# 地圖底圖與框線(與 tw-county-map 一致):海面淡藍底;縣市界深灰;鄉鎮界淺灰細線,再疊一層深灰縣市界,層級一眼分得出來。# 原本界線是白色,低值的淡色區域與白色背景混在一起,看不出海岸線與相鄰邊界。MAP_SEA = "#e4eef7"MAP_EDGE = "#5f6b7c"MAP_EDGE_TOWN = "#aab3bf"MAP_COUNTY_LINE = "#374151"NO_DATA_LABEL = "無資料"def _scheme_key(color_scheme) -> str:94 unmodified linescolors = px.colors.sample_colorscale(COLOR_SCALES[scheme], pos)return dict(zip(labels, (_to_hex(c) for c in colors)))def _is_town(merged) -> bool:"""鄉鎮市區層級的地圖資料才有「縣市」欄(load_map_file 加的)"""return '縣市' in getattr(merged, 'columns', [])def _edge_style(merged) -> Tuple[str, float]:return (MAP_EDGE_TOWN, 0.4) if _is_town(merged) else (MAP_EDGE, 0.6)def _add_county_outline(fig, merged, geo="geo"):"""鄉鎮圖疊上縣市界(深灰)。只畫圖上有的縣市,fitbounds 才不會被撐大"""if not _is_town(merged): returnlon, lat = county_outline_lines(tuple(sorted(merged['縣市'].dropna().unique())))fig.add_trace(go.Scattergeo(lon=lon, lat=lat, mode="lines", geo=geo, hoverinfo="skip", showlegend=False,line=dict(color=MAP_COUNTY_LINE, width=1.6)))def _style_map_ax(ax):"""matplotlib 地圖軸:海面底色、不畫座標軸(set_axis_off 會連底色一起關掉,所以改成只隱藏刻度與邊框)"""ax.set_facecolor(MAP_SEA)ax.set_xticks([]); ax.set_yticks([])ax.set_xlabel(''); ax.set_ylabel('') # geopandas 會自動標「Geodetic latitude [degree]」for spine in ax.spines.values(): spine.set_visible(False)def _plot_county_outline(ax, merged):if not _is_town(merged): returncounty = _require_map("county")county[county['name'].isin(merged['縣市'].dropna().unique())].boundary.plot(ax=ax, color=MAP_COUNTY_LINE, linewidth=0.8)def _style_map_layout(fig, title: str, bottom_legend: bool = False, merged=None):fig.update_geos(fitbounds="locations", visible=False, bgcolor=MAP_SEA)color, width = _edge_style(merged)fig.update_traces(marker_line_width=width, marker_line_color=color, selector=dict(type="choropleth"))layout = dict(margin={"r": 0, "t": 50, "l": 0, "b": 40},height=750, autosize=True,95 unmodified linesshowscale=False, text=missing['name'],hovertemplate=f"%{{text}}<br>{NO_DATA_LABEL}<extra></extra>"))_style_map_layout(fig, title, merged=merged)else:labels, label_series = binnedmerged = merged.assign(分級=label_series)5 unmodified linescolor_discrete_map=palette, category_orders={'分級': order},projection="mercator", hover_name='name', hover_data={**hover_data, '分級': False})_style_map_layout(fig, title, bottom_legend=True, merged=merged)_add_county_outline(fig, merged)return add_region_picker(fig, merged, stats=[(value_col, merged[value_col])])def build_static_map(merged, value_col, title, scheme="紅色系", mode="連續", figsize=(12, 12),7 unmodified linesbinned = classify(merged[value_col], mode, edges=edges)if binned is None:vmin, vmax = vrange if vrange else (None, None)edge, lw = _edge_style(merged)merged.plot(column=value_col, cmap=MPL_CMAPS[scheme], linewidth=lw, ax=ax, edgecolor=edge,vmin=vmin, vmax=vmax, legend=True, legend_kwds={'shrink': 0.6, 'pad': cbar_pad},missing_kwds={'color': NO_DATA_COLOR, 'label': NO_DATA_LABEL})else:4 unmodified linesfor lab in labels + [NO_DATA_LABEL]:sub = merged[label_series == lab]if lab == NO_DATA_LABEL and sub.empty: continueif not sub.empty: sub.plot(ax=ax, color=palette[lab], linewidth=_edge_style(merged)[1], edgecolor=_edge_style(merged)[0])handles.append(Patch(facecolor=palette[lab], edgecolor='0.5', label=lab)) # 空級距也列在圖例,各幀圖例一致ax.legend(handles=handles, title=value_col, loc='lower right', fontsize=legend_size,title_fontsize=legend_size + 1)_plot_county_outline(ax, merged)font_kw = {'fontproperties': CUSTOM_FONT_PROP} if CUSTOM_FONT_PROP else {}ax.set_title(title, size=title_size, **font_kw)_style_map_ax(ax)return fig# === 統計摘要函式 (白底深字版) ===121 unmodified linesgeojson=geo_json, locations=merged.index, z=z, colorscale=scale, name=name,text=merged['name'], hovertemplate="%{text}<br>" + name + ": %{z:,.0f}<extra></extra>",showscale=True, colorbar=dict(orientation="h", x=x, y=0, len=0.4, thickness=10, title=name),geo="geo" if idx == 1 else "geo2", marker_line_width=_edge_style(merged)[1], marker_line_color=_edge_style(merged)[0]), row=1, col=idx)for g in ("geo", "geo2"): _add_county_outline(fig, merged, geo=g)geo_common = dict(visible=False, projection_type="mercator", fitbounds="locations", bgcolor=MAP_SEA)fig.update_layout(geo=dict(**geo_common, domain=dict(x=[0, 0.48], y=[0, 1])),geo2=dict(**geo_common, domain=dict(x=[0.52, 1], y=[0, 1])),8 unmodified linesISLAND_COUNTIES = ('金門縣', '連江縣', '澎湖縣')def _map_frame(df, col, time, agg_method, map_level_state, show_islands, scope=None):"""彙整指標並合併到地圖;關閉離島時移除金門/連江/澎湖,讓本島可以放大;鄉鎮層級可只畫某縣市(或縣市+相鄰縣市)"""target_gdf = _require_map(map_level_state)if map_level_state == "town" and scope_counties(scope):target_gdf = target_gdf[target_gdf['縣市'].isin(scope_counties(scope))]if not show_islands:target_gdf = target_gdf[~target_gdf['name'].str.startswith(ISLAND_COUNTIES)]return merge_geo(target_gdf, aggregate_by_region(df, col, time, agg_method))def _scope_prefix(map_level_state, scope) -> str:return f"{scope}・" if map_level_state == "town" and scope_counties(scope) else ""def generate_map(df, col, time, agg_method, color_scheme, class_mode, show_islands, map_scope, map_level_state, all_cols):_require_regions(df)col = _resolve_col(col, all_cols)try:merged = _map_frame(df, col, time, agg_method, map_level_state, show_islands, map_scope)fig = build_choropleth(merged, col, f"🗺️ {_scope_prefix(map_level_state, map_scope)}{col} - 地理分布圖({_period_label(time)})",scheme=_scheme_key(color_scheme), mode=class_mode)return fig, gr.Tabs(selected="tab_map")except Exception as e:raise gr.Error(f"繪圖失敗: {e}")def export_static_map(df, col, time, agg_method, color_scheme, class_mode, show_islands, map_scope, map_level_state, all_cols):_require_regions(df)col = _resolve_col(col, all_cols)try:merged = _map_frame(df, col, time, agg_method, map_level_state, show_islands, map_scope)fig = build_static_map(merged, col, f"{_scope_prefix(map_level_state, map_scope)}{col} - 地圖 ({_period_label(time)})",scheme=_scheme_key(color_scheme), mode=class_mode, figsize=(15, 15))path = _named_path(_map_stem(col, time, map_level_state), ".png")fig.savefig(path, dpi=200, bbox_inches='tight', facecolor='white')16 unmodified linesexcept Exception:return gr.update()def export_html_map(df, col, time, agg_method, color_scheme, class_mode, show_islands, map_scope, map_level_state, all_cols):fig, _ = generate_map(df, col, time, agg_method, color_scheme, class_mode, show_islands, map_scope, map_level_state, all_cols)path = _named_path(_map_stem(_resolve_col(col, all_cols), time, map_level_state, "(互動)"), ".html")fig.write_html(path, include_plotlyjs="cdn")return gr.update(value=path, visible=True)145 unmodified lines"宜蘭縣", "花蓮縣", "臺東縣", "澎湖縣", "金門縣", "連江縣"]# 接壤的縣市(由縣市輪廓的共用邊界算出再寫死,與 tw-county-map 同一份)。臺北市、嘉義市被鄰縣整個包住,手動補上;離島沒有鄰縣NEIGHBORS = {"基隆市": ["新北市"], "臺北市": ["新北市"], "新北市": ["臺北市", "基隆市", "桃園市", "宜蘭縣"],"桃園市": ["新北市", "新竹縣", "宜蘭縣"], "新竹市": ["新竹縣", "苗栗縣"],"新竹縣": ["新竹市", "桃園市", "苗栗縣", "臺中市", "宜蘭縣"], "苗栗縣": ["新竹市", "新竹縣", "臺中市"],"臺中市": ["新竹縣", "苗栗縣", "花蓮縣", "彰化縣", "南投縣", "宜蘭縣"], "彰化縣": ["臺中市", "雲林縣", "南投縣"],"南投縣": ["臺中市", "彰化縣", "雲林縣", "嘉義縣", "高雄市", "花蓮縣"], "雲林縣": ["彰化縣", "南投縣", "嘉義縣"],"嘉義市": ["嘉義縣"], "嘉義縣": ["嘉義市", "南投縣", "雲林縣", "臺南市", "高雄市"], "臺南市": ["嘉義縣", "高雄市"],"高雄市": ["南投縣", "嘉義縣", "臺南市", "屏東縣", "花蓮縣", "臺東縣"], "屏東縣": ["高雄市", "臺東縣"],"宜蘭縣": ["新北市", "桃園市", "新竹縣", "臺中市", "花蓮縣"], "花蓮縣": ["臺中市", "南投縣", "宜蘭縣", "高雄市", "臺東縣"],"臺東縣": ["屏東縣", "高雄市", "花蓮縣"],}NEIGHBOR_SUFFIX = "+相鄰縣市"MANUAL_LEVELS = ["縣市", "鄉鎮市區"]MANUAL_NATIONAL = "全國"# 鄉鎮範圍選項:全國、單一縣市、某縣市+相鄰縣市(看跨縣市的外溢、擴散)SCOPE_CHOICES = [MANUAL_NATIONAL] + DEFAULT_COUNTIES + [c + NEIGHBOR_SUFFIX for c in DEFAULT_COUNTIES if c in NEIGHBORS]def scope_counties(scope: str) -> Optional[List[str]]:"""範圍字串 → 縣市清單;全國(或不認得的值)回 None"""if scope in DEFAULT_COUNTIES: return [scope]if isinstance(scope, str) and scope.endswith(NEIGHBOR_SUFFIX):main = scope[:-len(NEIGHBOR_SUFFIX)]if main in NEIGHBORS: return [main] + NEIGHBORS[main]return NoneMANUAL_LABEL_MODES = ["名稱 + 內容", "僅內容", "僅名稱", "不顯示標籤"]MANUAL_COLORS = ["紅色系 🔴", "藍色系 🔵", "綠色系 🟢", "熱力圖 🔥"]MANUAL_COL_NAME, MANUAL_COL_CONTENT = "名稱", "填寫內容"28 unmodified lines"""目前表格要列出的名稱:縣市層級=22 縣市;鄉鎮層級=全國或某縣市底下的鄉鎮市區"""if level != "鄉鎮市區": return list(DEFAULT_COUNTIES)gdf = _town_gdf()if scope_counties(scope): gdf = gdf[gdf['縣市'].isin(scope_counties(scope))]order = {c: i for i, c in enumerate(DEFAULT_COUNTIES)}sort_cols = ['town_id'] if 'town_id' in gdf.columns else ['name']gdf = gdf.assign(_o=gdf['縣市'].map(order)).sort_values(['_o'] + sort_cols)75 unmodified linesn = normalize_name(raw)if n in names: return nif level == "鄉鎮市區":for c in scope_counties(scope) or []: # 範圍內先找主縣市、再找相鄰縣市(例如「東區」)if c + n in names: return c + ncands = short.get(n, [])if len(cands) == 1: return cands[0] # 全國範圍下,名稱唯一的鄉鎮可以只寫短名return None22 unmodified lines# --- 資料合併與繪圖 ---_COUNTY_OUTLINE_CACHE: Dict[Tuple[str, ...], Tuple[list, list]] = {}def county_outline_lines(counties: Tuple[str, ...] = ()) -> Tuple[list, list]:"""縣市界線的座標(以 None 分段),疊在鄉鎮圖上才看得出縣市邊界;counties 空=全部縣市"""if counties not in _COUNTY_OUTLINE_CACHE:gdf = _require_map("county")if counties: gdf = gdf[gdf['name'].isin(counties)]lon, lat = [], []for geom in gdf.geometry.boundary:for line in getattr(geom, "geoms", [geom]):xs, ys = line.xylon += list(xs) + [None]; lat += list(ys) + [None]_COUNTY_OUTLINE_CACHE[counties] = (lon, lat)return _COUNTY_OUTLINE_CACHE[counties]def _manual_frame(input_df, level, scope, show_islands=True, numeric=None):"""3 unmodified lines"""if level == "鄉鎮市區":target = _town_gdf()if scope_counties(scope): target = target[target['縣市'].isin(scope_counties(scope))]else:target = _require_map("county")if input_df is None or len(input_df) == 0: raise gr.Error("請至少填寫一個項目的內容")112 unmodified lines"""有填標題就用標題;沒填就用「縣市統計圖」「新北市鄉鎮市區統計圖」"""if (title or "").strip(): return title.strip()if level != "鄉鎮市區": return "縣市統計圖"return "全國鄉鎮市區統計圖" if not scope_counties(scope) else f"{scope}鄉鎮市區統計圖"def _manual_title(title: str, level: str, scope: str) -> str:if (title or "").strip(): return title.strip()if level != "鄉鎮市區": return "臺灣各縣市"return "全國各鄉鎮市區" if not scope_counties(scope) else f"{scope}各鄉鎮市區"def generate_manual_distribution_map(input_df, level, scope, title, color_scheme, label_mode, label_size, show_islands):merged, is_numeric = _manual_frame(input_df, level, scope, show_islands)10 unmodified linescategory_orders={"類別": cats + ([UNFILLED_LABEL] if (~merged["filled"]).any() else [])},projection="mercator", hover_name="name", hover_data={"類別": False})_style_map_layout(fig, title, bottom_legend=True, merged=merged)_add_county_outline(fig, merged) # 數值模式由 build_choropleth 疊縣市界filled = merged[merged["filled"]]if label_mode != "不顯示標籤" and not filled.empty:44 unmodified linescats, palette = _category_palette(merged, cats)for cat in cats + [UNFILLED_LABEL]:sub = merged[merged["類別"] == cat]if not sub.empty: sub.plot(ax=ax, color=palette[cat], edgecolor=_edge_style(merged)[0], linewidth=_edge_style(merged)[1])handles = [Patch(facecolor=palette[c], edgecolor="0.5", label=c) for c in cats]if handles: ax.legend(handles=handles, loc="lower right", fontsize=12)_plot_county_outline(ax, merged) # 數值模式由 build_static_map 疊縣市界font_kw = {"fontproperties": CUSTOM_FONT_PROP} if CUSTOM_FONT_PROP else {}ax.set_title(title, size=24, **font_kw)_style_map_ax(ax)ax.apply_aspect()fs = int(label_size) * 0.85451 unmodified linesmap_ax = fig.add_axes([map_x0 / W, map_y0 / H, (map_x1 - map_x0) / W, (map_y1 - map_y0) / H])for cls in ("none", "other", "top", "bottom"):sub = main[main["_class"] == cls]if not sub.empty: sub.plot(ax=map_ax, color=color_of[cls], edgecolor=MAP_EDGE, linewidth=0.6) # 圖卡維持白底,只把白色界線改深灰bx0, by0, bx1, by1 = main.total_boundsmap_ax.set_xlim(bx0 - 0.02, bx1 + 0.02); map_ax.set_ylim(by0 - 0.02, by1 + 0.02)map_ax.set_axis_off()666 unmodified lines)class_mode = gr.Dropdown(CLASS_MODES, label="分級方式", value=CLASS_MODES[0])show_islands = gr.Checkbox(label="顯示離島(金門、連江、澎湖)— 關閉後本島會放大", value=True)map_scope = gr.Dropdown(SCOPE_CHOICES, label="鄉鎮範圍(全國、單一縣市、或縣市+相鄰縣市;看跨縣市的外溢、擴散)",value=MANUAL_NATIONAL, visible=False)with gr.Row():btn_map = gr.Button("🔄 更新地圖", variant="primary", scale=2)btn_export_map = gr.Button("💾 匯出 PNG", variant="secondary")8 unmodified lineswith gr.Column(scale=1, min_width=300):with gr.Row():manual_level = gr.Radio(MANUAL_LEVELS, label="層級", value=MANUAL_LEVELS[0])manual_scope = gr.Dropdown(SCOPE_CHOICES, label="鄉鎮範圍(全國、單一縣市、或縣市+相鄰縣市)",value="臺北市", visible=False)manual_input_df = gr.Dataframe(value=manual_table("縣市", MANUAL_NATIONAL, {}),137 unmodified lines}""")map_inputs = [current_df, col_selector, time_selector, agg_method, color_scheme, class_mode,show_islands, map_scope, map_level_state, all_numeric_cols_state]# 範圍選單只在鄉鎮層級有意義map_level_state.change(fn=lambda lv: gr.update(visible=(lv == "town")), inputs=map_level_state, outputs=map_scope)file_input.change(fn=process_uploaded_file, inputs=file_input,
app.py+114-46