Download code/plot_results.py from eduzrh/helloworld: direct link, hf CLI and curl.
- Browser
- Download file 8.21 kB
-
https://huggingface.co/datasets/eduzrh/helloworld/resolve/main/code/plot_results.py
- Command line
-
hf download hf://datasets/eduzrh/helloworld/code/plot_results.py
-
curl -L -o plot_results.py https://huggingface.co/datasets/eduzrh/helloworld/resolve/main/code/plot_results.py
8.21 kB
| """结果汇总:趋势检验、图件输出。""" | |
| import json | |
| import os | |
| import numpy as np | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| from matplotlib.path import Path | |
| from matplotlib.patches import PathPatch | |
| from matplotlib.collections import PatchCollection | |
| BASE = os.path.dirname(os.path.abspath(__file__)) | |
| OUT = os.path.join(BASE, "results") | |
| FIG = os.path.join(BASE, "figures") | |
| os.makedirs(FIG, exist_ok=True) | |
| plt.rcParams.update({ | |
| "font.family": ["Noto Sans CJK SC", "DejaVu Sans"], | |
| "axes.unicode_minus": False, | |
| "axes.edgecolor": "#3a3f4b", | |
| "axes.labelcolor": "#22262e", | |
| "text.color": "#22262e", | |
| "xtick.color": "#4a505c", | |
| "ytick.color": "#4a505c", | |
| "axes.grid": True, | |
| "grid.color": "#e2e5ea", | |
| "grid.linewidth": 0.6, | |
| "figure.facecolor": "white", | |
| "axes.facecolor": "white", | |
| }) | |
| INK = "#12161d" | |
| CYAN = "#0a7ea4" | |
| AMBER = "#d98324" | |
| RED = "#c0392b" | |
| def theil_sen(x, y): | |
| x = np.asarray(x, float) | |
| y = np.asarray(y, float) | |
| sl = [] | |
| n = len(x) | |
| for i in range(n): | |
| for j in range(i + 1, n): | |
| if x[j] != x[i]: | |
| sl.append((y[j] - y[i]) / (x[j] - x[i])) | |
| return float(np.median(sl)) | |
| def mk_test(y): | |
| from scipy.stats import kendalltau | |
| x = np.arange(len(y)) | |
| tau, p = kendalltau(x, y) | |
| return float(tau), float(p) | |
| def load_land(): | |
| gj = json.load(open(os.path.join(BASE, "data", "land110.geojson"))) | |
| paths = [] | |
| for f in gj["features"]: | |
| g = f["geometry"] | |
| polys = g["coordinates"] if g["type"] == "MultiPolygon" else [g["coordinates"]] | |
| for poly in polys: | |
| for ring in poly: | |
| arr = np.array(ring) | |
| if len(arr) < 4: | |
| continue | |
| paths.append(Path(arr, closed=True)) | |
| return paths | |
| def draw_land(ax, lw=0.5, color="#9aa3b0", face="none"): | |
| for p in load_land(): | |
| ax.add_patch(PathPatch(p, facecolor=face, edgecolor=color, lw=lw, zorder=3)) | |
| def fig_series(annual): | |
| full = [a for a in annual if a["year"] < 2026] | |
| x = np.array([a["year"] for a in full]) | |
| y = np.array([a["cdhe_frac_mean"] for a in full]) * 100 | |
| slope = theil_sen(x, y) | |
| tau, p = mk_test(y) | |
| fig, ax = plt.subplots(figsize=(7.2, 3.6), dpi=200) | |
| ax.bar(x, y, color="#c9d6e2", width=0.72, zorder=2, label="年均值") | |
| roll = np.convolve(y, np.ones(5) / 5, mode="valid") | |
| ax.plot(x[2:-2], roll, color=CYAN, lw=2.0, zorder=4, label="5 年滑动平均") | |
| ax.plot(x, y[0] + slope * (x - x[0]), color=RED, lw=1.6, ls="--", zorder=5, | |
| label=f"Theil-Sen {slope:+.2f} 百分点/年") | |
| ax.set_xlim(1979, 2025.5) | |
| ax.set_ylabel("CDHE 影响的陆地面积占比 (%)") | |
| ax.set_xlabel("年份") | |
| ax.set_title("全球复合干热月面积占比,1979—2025", loc="left", fontsize=10.5, color=INK) | |
| ax.text(0.995, 0.02, f"Mann-Kendall tau={tau:.2f}, p={p:.1e}", | |
| transform=ax.transAxes, ha="right", va="bottom", fontsize=7.5, color="#5a616e") | |
| ax.legend(frameon=False, fontsize=7, loc="upper left") | |
| for s in ("top", "right"): | |
| ax.spines[s].set_visible(False) | |
| fig.tight_layout() | |
| fig.savefig(os.path.join(FIG, "fig1_series.png"), bbox_inches="tight") | |
| plt.close(fig) | |
| return dict(slope_pp_per_yr=slope, tau=tau, p=p) | |
| def fig_seasonal(monthly): | |
| full = [r for r in monthly if r["year"] < 2026] | |
| fig, ax = plt.subplots(figsize=(6.4, 3.2), dpi=200) | |
| for label, years, color in [("1979–1999", (1979, 1999), "#9fb3c8"), | |
| ("2000–2025", (2000, 2025), AMBER)]: | |
| mm = [[] for _ in range(12)] | |
| for r in full: | |
| if years[0] <= r["year"] <= years[1]: | |
| mm[r["month"] - 1].append(r["cdhe_frac"]) | |
| ax.plot(range(1, 13), [np.mean(v) * 100 for v in mm], marker="o", ms=3.5, | |
| lw=1.8, color=color, label=label) | |
| ax.set_xticks(range(1, 13)) | |
| ax.set_xticklabels(["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]) | |
| ax.set_ylabel("CDHE 影响的陆地面积占比 (%)") | |
| ax.set_xlabel("月份") | |
| ax.set_title("CDHE 面积占比的季节循环", loc="left", fontsize=10.5, color=INK) | |
| ax.legend(frameon=False, fontsize=7) | |
| for s in ("top", "right"): | |
| ax.spines[s].set_visible(False) | |
| fig.tight_layout() | |
| fig.savefig(os.path.join(FIG, "fig2_seasonal.png"), bbox_inches="tight") | |
| plt.close(fig) | |
| def fig_region(region): | |
| names = list(region) | |
| years = sorted({d["year"] for d in region[names[0]] if d["year"] < 2026}) | |
| M = np.full((len(names), len(years)), np.nan) | |
| for i, n in enumerate(names): | |
| d = {r["year"]: r["cdhe_frac"] for r in region[n]} | |
| for j, y in enumerate(years): | |
| if y in d: | |
| M[i, j] = d[y] * 100 | |
| fig, ax = plt.subplots(figsize=(7.4, 3.4), dpi=200) | |
| im = ax.imshow(M, aspect="auto", cmap="YlOrRd", interpolation="nearest", | |
| extent=[years[0] - 0.5, years[-1] + 0.5, len(names) - 0.5, -0.5]) | |
| ax.set_yticks(range(len(names))) | |
| ax.set_yticklabels(names, fontsize=7.5) | |
| ax.set_xlabel("年份") | |
| ax.grid(False) | |
| cb = fig.colorbar(im, ax=ax, pad=0.015, fraction=0.03) | |
| cb.set_label("CDHE 面积占比 (%)", fontsize=7.5) | |
| cb.ax.tick_params(labelsize=6.5) | |
| ax.set_title("各区域 CDHE 面积占比", loc="left", fontsize=10.5, color=INK) | |
| fig.tight_layout() | |
| fig.savefig(os.path.join(FIG, "fig3_regions.png"), bbox_inches="tight") | |
| plt.close(fig) | |
| return names, years, M | |
| def fig_state(lat, lon, spi, sti, cdhe, title, fname): | |
| la = np.array(lat) | |
| lo = np.array(lon) | |
| lo_s = ((lo + 180) % 360) - 180 | |
| order = np.argsort(lo_s) | |
| fig, ax = plt.subplots(figsize=(8.0, 4.2), dpi=200) | |
| ax.set_facecolor("#f4f6f8") | |
| val = np.where(cdhe == 1, 3, np.where(spi <= -1, 1, np.where(sti >= 1, 2, 0))).astype(float) | |
| val[cdhe == -1] = np.nan | |
| cmap = plt.matplotlib.colors.ListedColormap(["#eef1f4", "#4a90c2", "#d98324", "#c0392b"]) | |
| im = ax.pcolormesh(lo_s[order], la, val[:, order], cmap=cmap, vmin=0, vmax=3, | |
| shading="nearest", zorder=1) | |
| draw_land(ax, lw=0.4, color="#7b8390") | |
| ax.set_xlim(-180, 180) | |
| ax.set_ylim(-60, 85) | |
| ax.set_xticks([-150, -100, -50, 0, 50, 100, 150]) | |
| ax.set_yticks([-40, -20, 0, 20, 40, 60, 80]) | |
| ax.set_xlabel("经度") | |
| ax.set_ylabel("纬度") | |
| ax.grid(False) | |
| ax.set_title(title, loc="left", fontsize=10.5, color=INK) | |
| from matplotlib.patches import Patch | |
| ax.legend(handles=[Patch(color="#4a90c2", label="仅干 (SPI≤-1)"), | |
| Patch(color="#d98324", label="仅热 (STI≥1)"), | |
| Patch(color="#c0392b", label="复合(干且热)")], | |
| loc="lower left", fontsize=6.8, frameon=True, framealpha=0.9, ncol=3) | |
| fig.tight_layout() | |
| fig.savefig(os.path.join(FIG, fname), bbox_inches="tight") | |
| plt.close(fig) | |
| def main(): | |
| annual = json.load(open(os.path.join(OUT, "annual_series.json"))) | |
| monthly = json.load(open(os.path.join(OUT, "monthly_series.json"))) | |
| region = json.load(open(os.path.join(OUT, "region_series.json"))) | |
| latest = json.load(open(os.path.join(OUT, "latest_grid.json"))) | |
| stats = fig_series(annual) | |
| fig_seasonal(monthly) | |
| names, years, M = fig_region(region) | |
| fig_state(latest["lat"], latest["lon"], np.array(latest["spi"]), | |
| np.array(latest["sti"]), np.array(latest["cdhe"]), | |
| f"复合干热状态,{latest['year']}-{latest['month']:02d}", "fig4_state.png") | |
| region_trend = {} | |
| for n in names: | |
| d = {r["year"]: r["cdhe_frac"] for r in region[n] if r["year"] < 2026} | |
| xs = sorted(d) | |
| ys = np.array([d[y] for y in xs]) * 100 | |
| tau, p = mk_test(ys) | |
| region_trend[n] = dict(slope_pp_per_yr=theil_sen(xs, ys), tau=tau, p=p, | |
| first=float(np.mean(ys[:10])), last=float(np.mean(ys[-10:]))) | |
| out = dict(global_trend=stats, regional_trend=region_trend) | |
| json.dump(out, open(os.path.join(OUT, "trend_stats.json"), "w"), ensure_ascii=False, indent=2) | |
| print(json.dumps(out, ensure_ascii=False, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |