noaaplotter 1.0.1__tar.gz → 1.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/PKG-INFO +10 -2
  2. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/README.md +7 -1
  3. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/figures/plotly_daily.py +137 -17
  4. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/noaaplotter.py +129 -14
  5. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/sources/base.py +6 -0
  6. noaaplotter-1.1.1/noaaplotter/sources/cds.py +342 -0
  7. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/sources/open_meteo.py +43 -8
  8. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/utils/dataset.py +3 -3
  9. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter.egg-info/PKG-INFO +10 -2
  10. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter.egg-info/SOURCES.txt +1 -0
  11. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter.egg-info/requires.txt +2 -0
  12. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/pyproject.toml +6 -1
  13. noaaplotter-1.1.1/tests/test_cds_source.py +194 -0
  14. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/tests/test_plotly_figures.py +160 -0
  15. noaaplotter-1.0.1/noaaplotter/sources/cds.py +0 -168
  16. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/LICENSE +0 -0
  17. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/__init__.py +0 -0
  18. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/__main__.py +0 -0
  19. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/cli/__init__.py +0 -0
  20. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/figures/__init__.py +0 -0
  21. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/figures/plotly_heatmap.py +0 -0
  22. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/figures/plotly_monthly.py +0 -0
  23. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/figures/plotly_stripes.py +0 -0
  24. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/scripts/download_data.py +0 -0
  25. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/scripts/plot_daily.py +0 -0
  26. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/scripts/plot_monthly.py +0 -0
  27. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/sources/__init__.py +0 -0
  28. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/utils/__init__.py +0 -0
  29. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/utils/config.py +0 -0
  30. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/utils/download_utils.py +0 -0
  31. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/utils/plot_utils.py +0 -0
  32. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter/utils/utils.py +0 -0
  33. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter.egg-info/dependency_links.txt +0 -0
  34. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter.egg-info/entry_points.txt +0 -0
  35. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/noaaplotter.egg-info/top_level.txt +0 -0
  36. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/setup.cfg +0 -0
  37. {noaaplotter-1.0.1 → noaaplotter-1.1.1}/tests/test_polars_parity.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: noaaplotter
3
- Version: 1.0.1
3
+ Version: 1.1.1
4
4
  Summary: Package to plot fancy climate/weather data of NOAA
5
5
  Author-email: Ingmar Nitze <ingmar.nitze@awi.de>
6
6
  License: MIT
@@ -31,6 +31,8 @@ Requires-Dist: python-dotenv>=1.0.1
31
31
  Requires-Dist: plotly>=5.18
32
32
  Requires-Dist: narwhals>=1.20.1
33
33
  Requires-Dist: cdsapi>=0.7
34
+ Requires-Dist: xarray>=2024.02
35
+ Requires-Dist: netCDF4>=1.6
34
36
  Requires-Dist: typer>=0.9.0
35
37
  Provides-Extra: docs
36
38
  Requires-Dist: mkdocs>=1.6; extra == "docs"
@@ -43,7 +45,7 @@ A python package to create fancy plots with NOAA weather data (stations) and ERA
43
45
 
44
46
  <p align="center">
45
47
  <a href="https://pypi.org/project/noaaplotter/">
46
- <img src="https://img.shields.io/pypi/v/noaaplotter?label=version" alt="PyPI version">
48
+ <img src="https://img.shields.io/badge/version-v1.1.1-31ad52" alt="version">
47
49
  </a>
48
50
  <a href="https://pypi.org/project/noaaplotter/">
49
51
  <img src="https://img.shields.io/pypi/pyversions/noaaplotter" alt="Python versions">
@@ -123,6 +125,12 @@ noaaplotter download-data -o data/potsdam.parquet --source open_meteo -lat 52.4
123
125
 
124
126
  Data files are cached: re-running only fetches the missing dates.
125
127
 
128
+ The ERA5-backed sources (`--source open_meteo` / `cds`) additionally return
129
+ daily **wind** columns: `WSPD` (daily mean 10 m wind speed, m/s) and
130
+ `WDIR` (daily dominant direction in degrees, meteorological convention —
131
+ the direction the wind blows FROM; 0 = north). NOAA station data has no
132
+ equivalent, so both stay null for `--source noaa`.
133
+
126
134
  ### `noaaplotter plot-daily`
127
135
  Daily temperature (observed vs. climate mean ± 1σ, with anomaly fills) + precipitation (bars + 7-day rolling sum).
128
136
 
@@ -3,7 +3,7 @@ A python package to create fancy plots with NOAA weather data (stations) and ERA
3
3
 
4
4
  <p align="center">
5
5
  <a href="https://pypi.org/project/noaaplotter/">
6
- <img src="https://img.shields.io/pypi/v/noaaplotter?label=version" alt="PyPI version">
6
+ <img src="https://img.shields.io/badge/version-v1.1.1-31ad52" alt="version">
7
7
  </a>
8
8
  <a href="https://pypi.org/project/noaaplotter/">
9
9
  <img src="https://img.shields.io/pypi/pyversions/noaaplotter" alt="Python versions">
@@ -83,6 +83,12 @@ noaaplotter download-data -o data/potsdam.parquet --source open_meteo -lat 52.4
83
83
 
84
84
  Data files are cached: re-running only fetches the missing dates.
85
85
 
86
+ The ERA5-backed sources (`--source open_meteo` / `cds`) additionally return
87
+ daily **wind** columns: `WSPD` (daily mean 10 m wind speed, m/s) and
88
+ `WDIR` (daily dominant direction in degrees, meteorological convention —
89
+ the direction the wind blows FROM; 0 = north). NOAA station data has no
90
+ equivalent, so both stay null for `--source noaa`.
91
+
86
92
  ### `noaaplotter plot-daily`
87
93
  Daily temperature (observed vs. climate mean ± 1σ, with anomaly fills) + precipitation (bars + 7-day rolling sum).
88
94
 
@@ -5,6 +5,13 @@ climatological mean +/- std with red/blue fill, no-data shading, record
5
5
  markers) plus precipitation panel (bars, 7-day rolling sum, no-data shading,
6
6
  optional cumulative snowfall on a secondary axis).
7
7
 
8
+ When the data carries non-empty WSPD/WDIR columns a third "wind ribbon" row
9
+ is added: vertical position = wind direction (0-360 deg, N at top), marker
10
+ colour = wind speed (RdYlGn_r: green calm -> red gusty). No legend and no
11
+ colorbar anywhere — the hover shows "FROM x° · y m/s".
12
+ The wind row is NOT drawn when snow accumulation is active (the secondary
13
+ snow axis and the wind row would both own yaxis3).
14
+
8
15
  When `window=(start, end)` is given (the user's selected plotting period) the
9
16
  figure carries the ENTIRE observed series and only the initial view is limited
10
17
  to that window — users can zoom out manually to browse the full record.
@@ -20,6 +27,54 @@ C_HIGH = "#d6604d"
20
27
  C_LOW = "#4393c3"
21
28
  YEAR_BAND = "rgba(0,0,0,0.025)" # light grey per calendar year (even years white)
22
29
 
30
+ WIND_COLORSCALE = "RdYlGn_r" # low (calm) -> green, high (gusty) -> red
31
+ WIND_MAX_PAD = 1.25 # colour-bar cap = data max * this (rounded up to 1 m/s)
32
+ WIND_ROWS_HEIGHTS = {"2 rows": (0.6, 0.4), "3 rows": (0.5, 0.3, 0.2)}
33
+ DARKEN = 0.68 # per-dot outline: marker colour * DARKEN (same hue, ~32% darker)
34
+
35
+
36
+ def _wind_colorscale():
37
+ """Return a plotly-compatible list of (t, color) stops for the wind scale.
38
+
39
+ Low speed -> green (calm), high speed -> red (gusty). Sampled from
40
+ matplotlib's RdYlGn colormap reversed (at 1-t) so t=0 is green and
41
+ t=1 is red. The stops drive the per-dot fill color AND its darkened
42
+ outline (same fill * DARKEN) — the speed value reaches the marker as
43
+ rgb strings so the trace carries NO colorscale and therefore no colorbar.
44
+ """
45
+ import matplotlib
46
+ cmap = matplotlib.colormaps["RdYlGn"]
47
+ scale = []
48
+ for i in range(10):
49
+ t = i / 9.0
50
+ r, g, b = (int(c * 255) for c in cmap(1.0 - t)[:3])
51
+ scale.append([t, f"rgb({r},{g},{b})"])
52
+ return scale
53
+
54
+
55
+ def _scale_color(scale, t):
56
+ """Interpolated 'rgb(r,g,b)' for scale position t (0..1)."""
57
+ t = min(max(float(t), 0.0), 1.0)
58
+ pos = t * (len(scale) - 1)
59
+ i0 = int(pos)
60
+ i1 = min(i0 + 1, len(scale) - 1)
61
+ w = pos - i0
62
+ def _rgb(s):
63
+ import re
64
+ return tuple(int(x) for x in re.match(
65
+ r"rgb\((\d+),(\d+),(\d+)\)", s).groups())
66
+ c0, c1 = _rgb(scale[i0][1]), _rgb(scale[i1][1])
67
+ r, g, b = (round(c0[k] * (1 - w) + c1[k] * w) for k in range(3))
68
+ return f"rgb({r},{g},{b})"
69
+
70
+
71
+ def _dark_rgb(rgb_str):
72
+ """Same colour, DARKEN factor darker (per-dot outline)."""
73
+ import re
74
+ r, g, b = (int(x) for x in re.match(
75
+ r"rgb\((\d+),(\d+),(\d+)\)", rgb_str).groups())
76
+ return f"rgb({int(r * DARKEN)},{int(g * DARKEN)},{int(b * DARKEN)})"
77
+
23
78
 
24
79
  def _clean(v):
25
80
  """Convert value to float or None if NaN."""
@@ -85,6 +140,12 @@ def make_daily_figure(df_obs, x_dates, x_dates_short, y_clim, y_clim_hi, y_clim_
85
140
  window : (start, end) timestamps, optional
86
141
  Initial visible x-range. When set, the full observed series is shown
87
142
  and only the initial view is clipped to this period.
143
+
144
+ wind : When ``df_obs`` contains non-null ``WSPD`` and ``WDIR`` columns,
145
+ a third row is drawn: ``wind ribbon`` (vertical = direction 0-360,
146
+ colour = speed). The ``show_snow_accumulation`` secondary axis
147
+ and the wind row both need ``yaxis3`` so only one of them will be
148
+ drawn at a time; the wind row wins (snowfall overlay is skipped).
88
149
  """
89
150
  if x_dates_short is not None:
90
151
  dates = list(x_dates_short["DATE"])
@@ -113,11 +174,26 @@ def make_daily_figure(df_obs, x_dates, x_dates_short, y_clim, y_clim_hi, y_clim_
113
174
  # y-range must include it so the full line is visible initially)
114
175
  prcp_rolling = pd.Series(prcp).rolling(window=7, min_periods=1, center=True).sum()
115
176
 
116
- fig = make_subplots(rows=2, cols=1, shared_xaxes=True,
117
- row_heights=[0.6, 0.4], vertical_spacing=0.07)
177
+ # ---- Wind row (row 3 of 3, when available and snow accumulation is off) ----
178
+ # WSPD/WDIR are the canonical ERA5 columns; NOAA station files do NOT
179
+ # carry them, so the row is drawn only when the data actually has wind.
180
+ has_wind = (
181
+ "WSPD" in df_obs.columns
182
+ and "WDIR" in df_obs.columns
183
+ and pd.Series(df_obs["WSPD"]).notna().any()
184
+ and pd.Series(df_obs["WDIR"]).notna().any()
185
+ )
186
+ # Snow accumulation pins yaxis3; it must be off for the wind row to render.
187
+ snow_active = bool(show_snow_accumulation and snow_dates is not None)
188
+ add_wind_row = bool(has_wind and not snow_active)
189
+ n_rows = 3 if add_wind_row else 2
190
+ row_heights = WIND_ROWS_HEIGHTS[f"{n_rows} rows"]
118
191
 
119
- # --- calendar-year background bands (light grey / white), both panels
120
- for row in (1, 2):
192
+ fig = make_subplots(rows=n_rows, cols=1, shared_xaxes=True,
193
+ row_heights=list(row_heights), vertical_spacing=0.07)
194
+
195
+ # --- calendar-year background bands (light grey / white) on drawn rows
196
+ for row in range(1, n_rows + 1):
121
197
  _add_year_bands(fig, dates, row)
122
198
 
123
199
  # --- temperature: soft light-grey climatological +/- sigma envelope (no hover)
@@ -132,25 +208,26 @@ def make_daily_figure(df_obs, x_dates, x_dates_short, y_clim, y_clim_hi, y_clim_
132
208
  upper_out = np.fmax(obs, clim_hi)
133
209
  lower_out = np.fmin(obs, clim_lo)
134
210
  fig.add_trace(_fill_band(dates, clim, upper_in, C_HIGH, 0.3,
135
- name="Above average Temperature",
136
- showlegend=True), 1, 1)
211
+ name="Above average Temperature"), 1, 1)
212
+ # secondary (>1 sigma) anomaly bands share the same hue as the main bands
213
+ # (no legend anywhere — still toggleable, still in hover)
137
214
  fig.add_trace(_fill_band(dates, clim_hi, upper_out, C_HIGH, 0.7,
138
- name="Above average Temperature (> 1 std)",
139
- showlegend=True), 1, 1)
215
+ name="Above average Temperature (> 1 std)"), 1, 1)
140
216
  fig.add_trace(_fill_band(dates, lower_in, clim, C_LOW, 0.3,
141
- name="Below average Temperature",
142
- showlegend=True), 1, 1)
217
+ name="Below average Temperature"), 1, 1)
143
218
  fig.add_trace(_fill_band(dates, lower_out, clim_lo, C_LOW, 0.7,
144
219
  name="Below average Temperature (> 1 std)",
145
- showlegend=True), 1, 1)
220
+ showlegend=False), 1, 1)
146
221
  # --- reference lines + observed (visual weight matched to the static render:
147
222
  # normals lw=2 @ 50% alpha, observed lw=1.2 @ 40% alpha,
148
223
  # sigma edges lw=1 @ 40% alpha). Hover values truncated to 2 decimals.
149
224
  fig.add_trace(go.Scatter(x=xfull, y=clim_full, name="Climatological Mean",
150
225
  line=dict(color="rgba(0,0,0,0.5)", width=2),
226
+ showlegend=False,
151
227
  hovertemplate="Climatology: %{y:.2f} °C<extra></extra>"), 1, 1)
152
228
  fig.add_trace(go.Scatter(x=xfull, y=clim_hi_full, name="Std of Climatological Mean",
153
229
  line=dict(color="rgba(0,0,0,0.4)", width=1, dash="dot"),
230
+ showlegend=False,
154
231
  hovertemplate="Upper 1σ: %{y:.2f} °C<extra></extra>"), 1, 1)
155
232
  fig.add_trace(go.Scatter(x=xfull, y=clim_lo_full, showlegend=False,
156
233
  line=dict(color="rgba(0,0,0,0.4)", width=1, dash="dot"),
@@ -172,7 +249,7 @@ def make_daily_figure(df_obs, x_dates, x_dates_short, y_clim, y_clim_hi, y_clim_
172
249
  fig.add_trace(go.Bar(x=nan_t, y=[span_hi - span_lo] * len(nan_t),
173
250
  base=span_lo, width=1,
174
251
  marker_color="rgba(0,0,0,0.2)",
175
- name="No Data", showlegend=True), 1, 1)
252
+ name="No Data", showlegend=False), 1, 1)
176
253
  fig.add_hline(y=0, line=dict(color="rgba(0,0,0,0.5)", dash="dash"), row=1, col=1)
177
254
 
178
255
  # --- temperature: record extremes
@@ -205,20 +282,23 @@ def make_daily_figure(df_obs, x_dates, x_dates_short, y_clim, y_clim_hi, y_clim_
205
282
  if nan_p:
206
283
  fig.add_trace(go.Bar(x=nan_p, y=[prcp_top] * len(nan_p), base=0, width=1,
207
284
  marker_color="rgba(0,0,0,0.2)",
208
- name="No Data", showlegend=True), 2, 1)
285
+ name="No Data", showlegend=False), 2, 1)
209
286
 
210
287
  # --- rolling 7-day precipitation sum
211
288
  # Convert to list for Plotly
212
289
  prcp_rolling_list = list(prcp_rolling.where(pd.notna(prcp_rolling)))
213
290
  fig.add_trace(go.Scatter(x=dates, y=prcp_rolling_list,
214
291
  name="7-Day Rolling Sum of Precipitation",
292
+ showlegend=False,
215
293
  line=dict(color="rgba(30,144,255,0.7)", width=2),
216
294
  hovertemplate="7-day Rolling Sum: %{y:.2f} mm<extra></extra>"), 2, 1)
217
295
 
218
296
  # --- snowfall accumulation: its OWN secondary axis on the precipitation row.
219
297
  # NOTE: add_trace() WITHOUT row/col on purpose — subplot row/col pinning would
220
298
  # force the trace onto the precipitation axis (y2) and hide the rain bars.
221
- if show_snow_accumulation and snow_dates is not None:
299
+ # Snow and the wind row both need yaxis3, so when the wind row is drawn the
300
+ # snowfall overlay is skipped (wind wins; it is the more recent feature).
301
+ if show_snow_accumulation and snow_dates is not None and not add_wind_row:
222
302
  snow_max = float(np.nanmax(snow_acc) / 10) if np.nanmax(snow_acc) > 0 else 1.0
223
303
  snow_top = plot_snowmax if plot_snowmax is not None else snow_max * 1.1
224
304
  fig.add_trace(go.Scatter(x=list(snow_dates),
@@ -237,11 +317,51 @@ def make_daily_figure(df_obs, x_dates, x_dates_short, y_clim, y_clim_hi, y_clim_
237
317
  line=dict(color="black", width=1, dash="dash"),
238
318
  showlegend=False, yaxis="y3"))
239
319
 
320
+ # --- wind ribbon (row 3): vertical position = wind DIRECTION (0-360 deg,
321
+ # N at top), colour = wind SPEED (green calm -> red gusty, colorbar in
322
+ # m/s). The figure legend is removed entirely; hover carries the exact
323
+ # "FROM x° · y m/s" values.
324
+ # Connector line is a faint hair-line so the dots read; per-dot outline is
325
+ # a slightly darkened copy of each dot's own fill color for crisp edges.
326
+ if add_wind_row:
327
+ wspd = np.asarray(df_obs["WSPD"], dtype=float)
328
+ wdir = np.asarray(df_obs["WDIR"], dtype=float)
329
+ scale = _wind_colorscale()
330
+ vmax = float(np.nanmax(wspd)) if np.isfinite(np.nanmax(wspd)) else 0.0
331
+ vmax = max(np.ceil(vmax * WIND_MAX_PAD), 1.0)
332
+ hover = (
333
+ "%{x|%Y-%m-%d}<br>FROM %{customdata[0]:.0f} deg"
334
+ " - %{customdata[1]:.1f} m/s<extra>WIND</extra>"
335
+ )
336
+ custom = list(zip(np.round(wdir, 0), np.round(wspd, 1)))
337
+ # per-dot rgb fill (no colorscale on the trace -> NO colorbar)
338
+ fill = [
339
+ None if not np.isfinite(v) else _scale_color(scale, v / vmax)
340
+ for v in wspd
341
+ ]
342
+ outline = [None if c is None else _dark_rgb(c) for c in fill]
343
+ fig.add_trace(go.Scatter(
344
+ x=dates, y=list(pd.Series(wdir).where(pd.notna(wdir))),
345
+ mode="lines+markers", name="WIND",
346
+ line=dict(width=1, color="rgba(30,45,70,0.30)"),
347
+ marker=dict(size=6, color=fill,
348
+ line=dict(width=0.8, color=outline)),
349
+ customdata=custom, hovertemplate=hover, showlegend=False),
350
+ 3, 1)
351
+ # headroom above N / below S (mirror of the static render) so extreme
352
+ # direction dots are not glued to the axis edge
353
+ fig.update_yaxes(range=[375, -15], title="Direction", row=3, col=1,
354
+ tickmode="array",
355
+ tickvals=[0, 45, 90, 135, 180, 225, 270, 315],
356
+ ticktext=["N", "NE", "E", "SE", "S", "SW", "W", "NW"])
357
+ for a in (0, 45, 90, 135, 180, 225, 270, 315):
358
+ fig.add_hline(y=a, line=dict(color="rgba(0,0,0,0.10)", dash="dot"),
359
+ row=3, col=1)
360
+
240
361
  layout = dict(height=figsize[1], width=figsize[0],
241
362
  template="plotly_white", hovermode="x unified",
242
- showlegend=True,
243
- legend=dict(orientation="h", yanchor="bottom", y=1.02,
244
- xanchor="left", x=0),
363
+ # legend removed entirely (hover + axis labels carry the info)
364
+ showlegend=False,
245
365
  margin=dict(l=40, r=40, t=50 if title else 40, b=30),
246
366
  title=dict(text=title, y=0.98) if title else None,
247
367
  xaxis_rangeslider_visible=False,
@@ -355,9 +355,42 @@ class NOAAPlotter(object):
355
355
  return fig_pl
356
356
 
357
357
  # ----- matplotlib rendering below -----
358
+ # Detect wind (WSPD + WDIR, non-null) → add a third row (wind ribbon).
359
+ has_wind_mpl = (
360
+ "WSPD" in df_obs.columns
361
+ and "WDIR" in df_obs.columns
362
+ and pd.Series(df_obs["WSPD"]).notna().any()
363
+ and pd.Series(df_obs["WDIR"]).notna().any()
364
+ )
365
+ n_rows_mpl = 3 if has_wind_mpl else 2
366
+ # shared font sizes: axis labels and tick labels read one size smaller
367
+ # than matplotlib's default
368
+ label_fontsize = "small"
369
+ tick_fontsize = "x-small"
358
370
  fig = plt.figure(figsize=figsize, dpi=dpi)
359
- ax_t = fig.add_subplot(211)
360
- ax_p = fig.add_subplot(212, sharex=ax_t)
371
+ # fixed, IDENTICAL horizontal margins for every row: all panels share
372
+ # the exact same width and every y-label sits at the same global x.
373
+ # (tight_layout would re-derive margins per-label; legend/titles sit
374
+ # outside the axes, so the margins are pinned explicitly instead.)
375
+ fig.subplots_adjust(left=0.09, right=0.985, top=0.90, bottom=0.18)
376
+ if has_wind_mpl:
377
+ # explicit vertical bands: temp, gap, precip, gap, wind (hspace 0 —
378
+ # every gap comes from a spacer row, so the temp/precip gap stays
379
+ # tight while the wind row keeps room for its speed-scale legend)
380
+ gs = fig.add_gridspec(
381
+ 5, 1,
382
+ height_ratios=[0.42, 0.05, 0.28, 0.16, 0.15],
383
+ hspace=0.0,
384
+ )
385
+ ax_t = fig.add_subplot(gs[0, 0])
386
+ ax_p = fig.add_subplot(gs[2, 0], sharex=ax_t)
387
+ ax_w = fig.add_subplot(gs[4, 0], sharex=ax_t)
388
+ else:
389
+ gs = fig.add_gridspec(
390
+ 2, 1, height_ratios=[0.6, 0.4], hspace=0.3,
391
+ )
392
+ ax_t = fig.add_subplot(gs[0, 0])
393
+ ax_p = fig.add_subplot(gs[1, 0], sharex=ax_t)
361
394
 
362
395
  # climate series (red line)
363
396
  (cm,) = ax_t.plot(x_dates["DATE"].values, y_clim.values, c="k", alpha=0.5, lw=2)
@@ -451,8 +484,9 @@ class NOAAPlotter(object):
451
484
  ax_t.set_xlim(start_date, end_date)
452
485
  if not (plot_tmin == "auto" and plot_tmin == "auto"):
453
486
  ax_t.set_ylim(plot_tmin, plot_tmax)
454
- ax_t.set_ylabel("Temperature in °C")
455
- ax_t.set_xlabel("Date")
487
+ ax_t.set_ylabel("Temperature in °C", fontsize=label_fontsize)
488
+ ax_t.set_xlabel("Date", fontsize=label_fontsize)
489
+ plt.setp(ax_t.get_yticklabels(), fontsize=tick_fontsize)
456
490
  if title:
457
491
  ax_t.set_title(title)
458
492
 
@@ -487,8 +521,9 @@ class NOAAPlotter(object):
487
521
  # grid
488
522
  ax_p.grid()
489
523
  # labels
490
- ax_p.set_ylabel("Precipitation in mm")
491
- ax_p.set_xlabel("Date")
524
+ ax_p.set_ylabel("Precipitation in mm", fontsize=label_fontsize)
525
+ ax_p.set_xlabel("Date", fontsize=label_fontsize)
526
+ plt.setp(ax_p.get_yticklabels(), fontsize=tick_fontsize)
492
527
  # y-axis scaling
493
528
  ax_p.set_ylim(bottom=0)
494
529
  if isinstance(plot_pmax, (int, float)):
@@ -514,7 +549,9 @@ class NOAAPlotter(object):
514
549
  ls="--",
515
550
  )
516
551
  # y-axis label
517
- ax2_snow.set_ylabel("Cumulative Snowfall in cm")
552
+ ax2_snow.set_ylabel("Cumulative Snowfall in cm",
553
+ fontsize=label_fontsize)
554
+ plt.setp(ax2_snow.get_yticklabels(), fontsize=tick_fontsize)
518
555
  # legend
519
556
  legend_handle_p.append(sn_acc)
520
557
  legend_text_p.append("Cumulative Snowfall")
@@ -571,13 +608,91 @@ class NOAAPlotter(object):
571
608
  locator = dates.MonthLocator()
572
609
  ax_t.xaxis.set_major_locator(locator)
573
610
  ax_p.xaxis.set_major_locator(locator)
574
- plt.setp(
575
- ax_t.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor"
576
- )
577
- plt.setp(
578
- ax_p.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor"
579
- )
580
- fig.tight_layout()
611
+ # All rows share one x-axis: only the bottommost panel carries date
612
+ # tick labels + the "Date" xlabel — otherwise each row's labels are
613
+ # occluded by the panel below them.
614
+ plt.setp(ax_t.get_xticklabels(), visible=False)
615
+ plt.setp(ax_p.get_xticklabels(), visible=False)
616
+ ax_t.set_xlabel("")
617
+ ax_p.set_xlabel("")
618
+ if has_wind_mpl:
619
+ plt.setp(
620
+ ax_w.get_xticklabels(), rotation=45, ha="right",
621
+ rotation_mode="anchor", fontsize=tick_fontsize,
622
+ )
623
+ ax_w.set_xlabel("Date", fontsize=label_fontsize)
624
+ else:
625
+ plt.setp(
626
+ ax_p.get_xticklabels(), rotation=45, ha="right",
627
+ rotation_mode="anchor", fontsize=tick_fontsize,
628
+ )
629
+ ax_p.set_xlabel("Date", fontsize=label_fontsize)
630
+
631
+ # --- wind ribbon (third row, when source carries WSPD + WDIR) ---
632
+ # Vertical position = DIRECTION (0-360 deg, N at top); colour = SPEED
633
+ # (green calm -> red gusty). Matches the plotly wind-row mapping.
634
+ # No colorbar (it would shrink the wind axis and break the width match
635
+ # with the rows above): the speed scale lives in a small landscape
636
+ # legend INSIDE the wind panel instead.
637
+ if has_wind_mpl:
638
+ import matplotlib
639
+ from matplotlib.colors import Normalize
640
+ from matplotlib.lines import Line2D
641
+ wspd_w = np.asarray(df_obs["WSPD"], dtype=float)
642
+ wdir_w = np.asarray(df_obs["WDIR"], dtype=float)
643
+ cmap_w = matplotlib.colormaps["RdYlGn_r"] # green low -> red high
644
+ vmax_w = (
645
+ max(float(np.nanmax(wspd_w)) * 1.25, 1.0)
646
+ if np.isfinite(np.nanmax(wspd_w)) else 1.0
647
+ )
648
+ norm_w = Normalize(vmin=0.0, vmax=vmax_w)
649
+ sc = ax_w.scatter(
650
+ x_dates_short["DATE"].values,
651
+ wdir_w,
652
+ s=12, c=wspd_w, cmap=cmap_w, norm=norm_w,
653
+ edgecolors="none",
654
+ )
655
+ # faint connector line (thin, grey) under the dots
656
+ ax_w.plot(
657
+ x_dates_short["DATE"].values, wdir_w,
658
+ color=(30/255, 45/255, 70/255, 0.30), linewidth=0.8,
659
+ )
660
+ # headroom above N and below S so extreme dots are not glued to
661
+ # the axis edge
662
+ ax_w.set_ylim(375, -15)
663
+ # 4 cardinal ticks only: the wind row is short, 8 compass ticks
664
+ # would collide vertically
665
+ ax_w.set_yticks([0, 90, 180, 270])
666
+ ax_w.set_yticklabels(["N", "E", "S", "W"])
667
+ plt.setp(ax_w.get_yticklabels(), fontsize=tick_fontsize)
668
+ ax_w.set_ylabel("Direction", fontsize=label_fontsize)
669
+ ax_w.yaxis.grid(True, linestyle=":", alpha=0.5)
670
+ ax_w.xaxis.set_major_locator(locator)
671
+ plt.setp(
672
+ ax_w.get_xticklabels(),
673
+ rotation=45, ha="right", rotation_mode="anchor",
674
+ )
675
+ ax_w.set_xlabel("Date")
676
+ # speed scale as 4 discrete bins; landscape legend placed ABOVE the
677
+ # wind panel (in the gap below the precipitation panel), mirroring
678
+ # the temperature legend style
679
+ n_bins = 4
680
+ speed_handles, speed_labels = [], []
681
+ for i in range(n_bins):
682
+ lo_b, hi_b = vmax_w * i / n_bins, vmax_w * (i + 1) / n_bins
683
+ speed_handles.append(Line2D(
684
+ [], [], marker="o", ls="none", markersize=5,
685
+ color=cmap_w((i + 0.5) / n_bins),
686
+ ))
687
+ speed_labels.append(f"{lo_b:.0f}-{hi_b:.0f}")
688
+ leg_w = ax_w.legend(
689
+ speed_handles, speed_labels,
690
+ loc="lower center", ncol=n_bins, fontsize=legend_fontsize,
691
+ title="Wind speed (m/s)",
692
+ bbox_to_anchor=(0.5, 1.02),
693
+ )
694
+ # match the legend text font of the temperature/precipitation panels
695
+ leg_w.get_title().set_fontsize(legend_fontsize)
581
696
 
582
697
  # Save Figure
583
698
  if save_path:
@@ -3,6 +3,12 @@
3
3
  Every source fetches daily weather data and maps it into the canonical
4
4
  schema (the parquet NOAA downloader already writes), so downstream
5
5
  (plotting, climate stats) is schema-agnostic.
6
+
7
+ Optional extension: ERA5-backed sources (open_meteo, cds) additionally
8
+ provide WSPD (daily mean 10 m wind speed, m/s) and WDIR (daily dominant
9
+ wind direction, degrees, meteorological FROM-convention, 0 = north).
10
+ NOAA station data has no equivalent, so they are not required by
11
+ CANONICAL_COLUMNS.
6
12
  """
7
13
  import polars as pl
8
14