Download code/fig_case.py from eduzrh/helloworld: direct link, hf CLI and curl.
- Browser
- Download file 3.64 kB
-
https://huggingface.co/datasets/eduzrh/helloworld/resolve/main/code/fig_case.py
- Command line
-
hf download hf://datasets/eduzrh/helloworld/code/fig_case.py
-
curl -L -o fig_case.py https://huggingface.co/datasets/eduzrh/helloworld/resolve/main/code/fig_case.py
3.64 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, Patch | |
| BASE = os.path.dirname(os.path.abspath(__file__)) | |
| OUT = os.path.join(BASE, "results") | |
| FIG = os.path.join(BASE, "figures") | |
| plt.rcParams.update({ | |
| "font.family": ["Noto Sans CJK SC", "DejaVu Sans"], | |
| "axes.unicode_minus": False, | |
| "axes.edgecolor": "#3a3f4b", | |
| "text.color": "#22262e", | |
| "xtick.color": "#4a505c", | |
| "ytick.color": "#4a505c", | |
| "figure.facecolor": "white", | |
| }) | |
| CMAP = ["#eef1f4", "#4a90c2", "#d98324", "#c0392b"] | |
| 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: | |
| paths.append(Path(arr, closed=True)) | |
| return paths | |
| LAND = load_land() | |
| def panel(ax, lat, lon, spi, sti, title, sub): | |
| lo_s = ((lon + 180) % 360) - 180 | |
| order = np.argsort(lo_s) | |
| val = np.where((spi <= -1) & (sti >= 1), 3, np.where(spi <= -1, 1, np.where(sti >= 1, 2, 0))).astype(float) | |
| nan = np.isnan(spi) | np.isnan(sti) | |
| val[nan] = np.nan | |
| ax.set_facecolor("#f4f6f8") | |
| ax.pcolormesh(lo_s[order], lat, val[:, order], cmap=plt.matplotlib.colors.ListedColormap(CMAP), | |
| vmin=0, vmax=3, shading="nearest") | |
| for p in LAND: | |
| ax.add_patch(PathPatch(p, facecolor="none", edgecolor="#7b8390", lw=0.35, zorder=3)) | |
| 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.grid(False) | |
| ax.set_title(f"{title} {sub}", loc="left", fontsize=9.2, color="#12161d") | |
| def main(): | |
| import netCDF4 as nc | |
| d = nc.Dataset(os.path.join(BASE, "data", "precip.mon.mean.nc")) | |
| lat = np.array(d["lat"][:], float); lon = np.array(d["lon"][:], float) | |
| d.close() | |
| spi = np.load(os.path.join(OUT, "spi.npy")) | |
| sti = np.load(os.path.join(OUT, "sti.npy")) | |
| monthly = json.load(open(os.path.join(OUT, "monthly_series.json"))) | |
| def pick(y, m): | |
| return next(i for i, r in enumerate(monthly) if r["year"] == y and r["month"] == m) | |
| a = max([r for r in monthly if r["year"] == 2023], key=lambda r: r["cdhe_frac"]) | |
| b = max([r for r in monthly if r["year"] == 2024], key=lambda r: r["cdhe_frac"]) | |
| cases = [(a, f"{a['year']}-{a['month']:02d}"), (b, f"{b['year']}-{b['month']:02d}")] | |
| fig, axes = plt.subplots(2, 1, figsize=(7.6, 6.4), dpi=200) | |
| for ax, (r, lab) in zip(axes, cases): | |
| k = pick(r["year"], r["month"]) | |
| panel(ax, lat, lon, spi[k], sti[k], f"{lab}", | |
| f"CDHE {r['cdhe_frac']*100:.1f}% · 干 {r['dry_frac']*100:.1f}% · 热 {r['hot_frac']*100:.1f}%") | |
| fig.legend(handles=[Patch(color=CMAP[1], label="仅干 (SPI≤-1)"), | |
| Patch(color=CMAP[2], label="仅热 (STI≥1)"), | |
| Patch(color=CMAP[3], label="复合(干且热)")], | |
| loc="lower center", ncol=3, frameon=False, fontsize=7.5, bbox_to_anchor=(0.5, -0.01)) | |
| fig.tight_layout(rect=(0, 0.03, 1, 1)) | |
| fig.savefig(os.path.join(FIG, "fig5_cases.png"), bbox_inches="tight") | |
| plt.close(fig) | |
| print("ok", [(c[1], round(c[0]["cdhe_frac"] * 100, 1)) for c in cases]) | |
| if __name__ == "__main__": | |
| main() | |