helloworld / reproduction /code /make_figures.py
eduzrh's picture
完整复现 Blöschl et al. (2020, Nature):50 种子时空插值、事件识别排序、温度与季节性分析 + 文献综述 + 全部日志
bcd3cbd verified
Raw History Blame Contribute Delete
10.1 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Generate reproduction figures for Blöschl et al. (2020, Nature).
Inputs (produced by postprocess.R and the original data):
results/max10events.csv, results/temperature_summary.csv,
results/seasonality_summary.csv, data/sites.csv, data/i_f.csv
Outputs (300 dpi PNG + PDF) into figures/.
"""
import json
import os
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
HERE = os.path.dirname(os.path.abspath(__file__))
RES = os.path.join(HERE, '..', 'results')
DATA = os.path.join(HERE, '..', 'data')
FIG = os.path.join(HERE, '..', 'figures')
os.makedirs(FIG, exist_ok=True)
plt.rcParams.update({
'font.size': 9, 'axes.titlesize': 10, 'axes.labelsize': 9,
'figure.dpi': 300, 'savefig.dpi': 300, 'font.family': 'DejaVu Sans'
})
# ------------------------------------------------------------------ #
# Fig 1: data overview (series coverage + flood intensity classes)
# ------------------------------------------------------------------ #
sites = pd.read_csv(os.path.join(DATA, 'sites.csv'))
i_f = pd.read_csv(os.path.join(DATA, 'i_f.csv'))
bias = pd.read_csv(os.path.join(DATA, 'bias.csv'))
fig, axes = plt.subplots(1, 3, figsize=(10.5, 2.9))
# (a) site map (lon/lat scatter)
lon = np.where(sites['lon4'].astype(str).str.strip().str.upper().str.startswith('W'),
-(sites['lon1'] + sites['lon2'] / 60 + sites['lon3'] / 3600),
sites['lon1'] + sites['lon2'] / 60 + sites['lon3'] / 3600)
lat = sites['lat1'] + sites['lat2'] / 60 + sites['lat3'] / 3600
regname = {'c': 'Central', 'w': 'Western', 's': 'Southern', 'n': 'Northern', 'e': 'Eastern'}
regcol = {'c': '#d62728', 'w': '#1f77b4', 's': '#2ca02c', 'n': '#9467bd', 'e': '#ff7f0e'}
for reg in ['w', 'c', 's', 'n', 'e']:
m = sites['regionEU'] == reg
axes[0].scatter(lon[m], lat[m], s=14, c=regcol[reg], label=regname[reg], alpha=.85, linewidths=.3, edgecolors='k')
axes[0].set_xlabel('Longitude (°E)'); axes[0].set_ylabel('Latitude (°N)')
axes[0].set_title('(a) 103 historical flood series')
axes[0].legend(fontsize=6, loc='lower left', framealpha=.9)
# (b) number of series with data over time (bias index > 1)
years = bias['Year'].values
active = (bias.iloc[:, 1:] > 1).sum(axis=1).values
axes[1].fill_between(years, active, step='mid', alpha=.4)
axes[1].plot(years, active, lw=.8)
axes[1].set_xlabel('Year'); axes[1].set_ylabel('Number of series')
axes[1].set_title('(b) Series with source material')
# (c) flood counts by class and season
cnt = i_f[i_f['Index'].isin(['class1', 'class2', 'class3'])].copy()
class_counts = cnt['Index'].value_counts().reindex(['class1', 'class2', 'class3'])
bars = axes[2].bar(['Class 1\n(notable)', 'Class 2\n(great)', 'Class 3\n(extraordinary)'],
class_counts.values, color=['#9ecae1', '#4292c6', '#08519c'], edgecolor='k', linewidth=.5)
for b, v in zip(bars, class_counts.values):
axes[2].text(b.get_x() + b.get_width() / 2, v + 80, f'{v}', ha='center', fontsize=8)
axes[2].set_ylabel('Number of floods'); axes[2].set_title(f'(c) Flood intensity classes (N={len(cnt):,})')
fig.tight_layout()
fig.savefig(os.path.join(FIG, 'fig1_data_overview.png'), bbox_inches='tight')
fig.savefig(os.path.join(FIG, 'fig1_data_overview.pdf'), bbox_inches='tight')
plt.close(fig)
# ------------------------------------------------------------------ #
# Fig 2: flood-rich periods timeline (cf. Table 1 / Fig 1 of paper)
# ------------------------------------------------------------------ #
ev = pd.read_csv(os.path.join(RES, 'max10events.csv'))
ev = ev.sort_values('yr_st').reset_index(drop=True)
# rank colors: red (strong) -> blue (weak), rank 1 strongest
cmap = plt.get_cmap('coolwarm_r')
norm = plt.Normalize(vmin=1, vmax=10)
fig, ax = plt.subplots(figsize=(9.2, 3.4))
for _, r in ev.iterrows():
y = {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'Va': 5, 'Vb': 6, 'VI': 7, 'VII': 8, 'VIII': 9, 'IX': 10}[r['name']]
color = cmap(norm(r['rank']))
ax.barh(y, r['yr_en'] - r['yr_st'], left=r['yr_st'], height=.72, color=color,
edgecolor='k', linewidth=.6)
ax.text(r['yr_st'] + (r['yr_en'] - r['yr_st']) / 2, y, f"#{int(r['rank'])}",
ha='center', va='center', fontsize=7, color='white' if r['rank'] <= 4 else 'k', fontweight='bold')
ax.set_yticks(range(1, 11))
ax.set_yticklabels([n for n in ['I', 'II', 'III', 'IV', 'Va', 'Vb', 'VI', 'VII', 'VIII', 'IX']])
ax.set_xlabel('Year (CE)')
ax.set_title('Flood-rich periods in Europe since 1500 (reproduction; label = rank, 1 = strongest)')
ax.set_xlim(1490, 2030)
ax.invert_yaxis()
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
cb = fig.colorbar(sm, ax=ax, pad=.01, ticks=range(1, 11))
cb.set_label('Rank (1 = strongest)')
fig.tight_layout()
fig.savefig(os.path.join(FIG, 'fig2_flood_rich_periods.png'), bbox_inches='tight')
fig.savefig(os.path.join(FIG, 'fig2_flood_rich_periods.pdf'), bbox_inches='tight')
plt.close(fig)
# ------------------------------------------------------------------ #
# Fig 3: temperature anomalies, flood vs interflood periods (cf. Fig 4)
# ------------------------------------------------------------------ #
ts = pd.read_csv(os.path.join(RES, 'temperature_summary.csv'))
fig, axes = plt.subplots(1, 3, figsize=(10.5, 3.1), sharey=False)
panels = [('c', '(a) Central Europe', ['I', 'II', 'IV', 'Va', 'VII', 'IX']),
('w', '(b) Western Europe', ['I', 'II', 'IV', 'Va', 'VI', 'IX']),
('s', '(c) Southern Europe', ['III', 'Va', 'VI', 'IX'])]
for ax, (reg, title, order) in zip(axes, panels):
sub = ts[ts['region'] == reg].set_index('period')
flood = sub.loc[[p for p in order if p in sub.index]]
x = np.arange(len(flood))
ax.errorbar(x, flood['meanT'], yerr=[flood['meanT'] - flood['lower90'], flood['upper90'] - flood['meanT']],
fmt='o', ms=4, color='#d62728', label='flood-rich period', capsize=2)
# interflood periods: ItoII etc. map to position between
inter = sub[sub['kind'] == 'interflood']
xi, yi, yierr = [], [], []
for p in inter.index:
a = b = None
if p.startswith('STto'):
a, b = 'ST', p[len('STto'):]
elif p.endswith('toEND'):
a, b = p[:-len('toEND')], 'END'
elif 'to' in p:
a, b = p.split('to')
if a not in order or b not in order:
continue
i1 = order.index(a); i2 = order.index(b)
xi.append((i1 + i2) / 2)
yi.append(inter.loc[p, 'meanT'])
yierr.append(inter.loc[p, 'meanT'] - inter.loc[p, 'lower90'])
ax.errorbar(xi, yi, yerr=yierr, fmt='s', ms=4, color='#1f77b4', label='interflood period', capsize=2)
ax.axhline(0, color='gray', lw=.5, ls=':')
ax.set_xticks(range(len(order))); ax.set_xticklabels(order, fontsize=8)
ax.set_title(title); ax.set_xlabel('Flood-rich period')
if reg == 'c':
ax.set_ylabel('Temperature anomaly (°C, rel. 1961–1990)')
ax.legend(fontsize=6, loc='best')
fig.suptitle('Air temperature of flood-rich vs interflood periods (error bars: 90% CI)', y=1.02, fontsize=10)
fig.tight_layout()
fig.savefig(os.path.join(FIG, 'fig3_temperature.png'), bbox_inches='tight')
fig.savefig(os.path.join(FIG, 'fig3_temperature.pdf'), bbox_inches='tight')
plt.close(fig)
# ------------------------------------------------------------------ #
# Fig 4: seasonality (cf. Fig 5b / Extended Data Fig 5b-d)
# ------------------------------------------------------------------ #
ss = pd.read_csv(os.path.join(RES, 'seasonality_summary.csv'))
fig, axes = plt.subplots(1, 3, figsize=(10.5, 3.1), sharey=True)
panels = [('c', 'summer', '(a) Central Europe — summer'), ('s', 'autumn', '(b) Southern Europe — autumn'),
('w', 'winter', '(c) Western Europe — winter')]
group_order = ['noFrich', 'pastFrich', 'IX']
group_labels = ['interflood\nperiods', 'past flood-rich\nperiods', 'recent period\nIX (1990–2016)']
for ax, (reg, season, title) in zip(axes, panels):
sub = ss[(ss['region'] == reg) & (ss['season'] == season)].set_index('group').loc[group_order]
x = np.arange(3)
ax.bar(x, sub['p_hat'], yerr=[sub['p_hat'] - sub['lower90'], sub['upper90'] - sub['p_hat']],
capsize=3, color=['#1f77b4', '#2ca02c', '#d62728'], edgecolor='k', linewidth=.5, width=.62)
for xi, v in zip(x, sub['p_hat']):
ax.text(xi, v + .015, f'{v:.0%}', ha='center', fontsize=8)
ax.set_xticks(x); ax.set_xticklabels(group_labels, fontsize=7)
ax.set_ylim(0, .70); ax.set_title(title)
ax.set_ylabel('Weighted flood proportion' if reg == 'c' else '')
fig.suptitle('Seasonality of floods within and outside flood-rich periods (error bars: 90% CI)', y=1.02, fontsize=10)
fig.tight_layout()
fig.savefig(os.path.join(FIG, 'fig4_seasonality.png'), bbox_inches='tight')
fig.savefig(os.path.join(FIG, 'fig4_seasonality.pdf'), bbox_inches='tight')
plt.close(fig)
# ------------------------------------------------------------------ #
# Fig 5: all identified events (size vs strength, cf. Extended Data Fig 2)
# ------------------------------------------------------------------ #
alle = pd.read_csv(os.path.join(RES, 'all_events.csv'))
fig, ax = plt.subplots(figsize=(5.4, 3.6))
top10 = set(ev['id'])
for _, r in alle.iterrows():
is_top = r['id'] in top10
ax.scatter(r['volume_Mkm2yr'], r['meanstrength'], s=60 if is_top else 18,
c='#d62728' if is_top else 'gray', alpha=.9 if is_top else .45,
edgecolors='k', linewidths=.4, zorder=3 if is_top else 2)
for _, r in ev.iterrows():
ax.annotate(r['name'], (r['volume_Mkm2yr'], r['meanstrength']),
textcoords='offset points', xytext=(4, 4), fontsize=8, fontweight='bold')
ax.set_xlabel('Space–time extent (10⁶ km² yr)')
ax.set_ylabel('Mean flood intensity $i_i$')
ax.set_title('Identified flood-rich periods (red = top 10, named)')
fig.tight_layout()
fig.savefig(os.path.join(FIG, 'fig5_events_scatter.png'), bbox_inches='tight')
fig.savefig(os.path.join(FIG, 'fig5_events_scatter.pdf'), bbox_inches='tight')
plt.close(fig)
print('figures written to', FIG)