noaaplotter 1.0.0__py3-none-any.whl
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.
- noaaplotter/__init__.py +20 -0
- noaaplotter/__main__.py +8 -0
- noaaplotter/cli/__init__.py +186 -0
- noaaplotter/figures/__init__.py +5 -0
- noaaplotter/figures/plotly_daily.py +258 -0
- noaaplotter/figures/plotly_monthly.py +51 -0
- noaaplotter/noaaplotter.py +726 -0
- noaaplotter/scripts/download_data.py +150 -0
- noaaplotter/scripts/plot_daily.py +108 -0
- noaaplotter/scripts/plot_monthly.py +72 -0
- noaaplotter/sources/__init__.py +17 -0
- noaaplotter/sources/base.py +97 -0
- noaaplotter/sources/cds.py +168 -0
- noaaplotter/sources/open_meteo.py +108 -0
- noaaplotter/utils/__init__.py +0 -0
- noaaplotter/utils/config.py +30 -0
- noaaplotter/utils/dataset.py +418 -0
- noaaplotter/utils/download_utils.py +232 -0
- noaaplotter/utils/plot_utils.py +49 -0
- noaaplotter/utils/utils.py +110 -0
- noaaplotter-1.0.0.dist-info/METADATA +220 -0
- noaaplotter-1.0.0.dist-info/RECORD +26 -0
- noaaplotter-1.0.0.dist-info/WHEEL +5 -0
- noaaplotter-1.0.0.dist-info/entry_points.txt +5 -0
- noaaplotter-1.0.0.dist-info/licenses/LICENSE +21 -0
- noaaplotter-1.0.0.dist-info/top_level.txt +1 -0
noaaplotter/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""noaaplotter — plot NOAA / reanalysis weather data.
|
|
2
|
+
|
|
3
|
+
Public API:
|
|
4
|
+
from noaaplotter import NOAAPlotter
|
|
5
|
+
|
|
6
|
+
See the documentation for the full API reference and CLI reference.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
12
|
+
|
|
13
|
+
from noaaplotter.noaaplotter import NOAAPlotter
|
|
14
|
+
|
|
15
|
+
__all__ = ["NOAAPlotter", "__version__"]
|
|
16
|
+
|
|
17
|
+
try:
|
|
18
|
+
__version__ = version("noaaplotter")
|
|
19
|
+
except PackageNotFoundError: # installed without metadata (e.g. source checkout)
|
|
20
|
+
__version__ = "unknown"
|
noaaplotter/__main__.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""
|
|
2
|
+
CLI Commands for noaaplotter
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import typer
|
|
6
|
+
from typing import Optional, Tuple
|
|
7
|
+
|
|
8
|
+
# Import the core functionality
|
|
9
|
+
from noaaplotter.utils.config import get_noaa_token
|
|
10
|
+
from noaaplotter.utils.download_utils import download_from_noaa
|
|
11
|
+
from noaaplotter.noaaplotter import NOAAPlotter
|
|
12
|
+
from noaaplotter.sources import get_source
|
|
13
|
+
from noaaplotter.sources.open_meteo import save_to_parquet
|
|
14
|
+
|
|
15
|
+
# Create Typer app instance for commands
|
|
16
|
+
app = typer.Typer(no_args_is_help=True)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@app.command("download-data")
|
|
20
|
+
def download_data(
|
|
21
|
+
output_file: str = typer.Option(..., "-o", "--output-file", help="Output file path (parquet)"),
|
|
22
|
+
station_id: Optional[str] = typer.Option(None, "-sid", "--station-id", help='NOAA station id, e.g. "USW00026616" (Kotzebue)'),
|
|
23
|
+
latitude: Optional[float] = typer.Option(None, "-lat", "--latitude", help="Latitude for coordinate-based sources (required for open_meteo/cds)"),
|
|
24
|
+
longitude: Optional[float] = typer.Option(None, "-lon", "--longitude", help="Longitude for coordinate-based sources (required for open_meteo/cds)"),
|
|
25
|
+
start_date: str = typer.Option(..., "-start", "--start-date", help="Start date (YYYY-MM-DD)"),
|
|
26
|
+
end_date: str = typer.Option(..., "-end", "--end-date", help="End date (YYYY-MM-DD)"),
|
|
27
|
+
token: Optional[str] = typer.Option(None, "-t", "--token", help="NOAA token (optional; the public NCEI endpoint needs none). Defaults to NOAA_API_TOKEN from environment or .env if set"),
|
|
28
|
+
source: str = typer.Option("noaa", "--source", help="Data source: noaa, open_meteo, or cds"),
|
|
29
|
+
datatypes: str = typer.Option("TMIN,TMAX,PRCP,SNOW", "--datatypes", help="Comma-separated datatypes (NOAA only)"),
|
|
30
|
+
n_jobs: int = typer.Option(1, "-n_jobs", "--n-jobs", help="Number of parallel processes (NOAA only)"),
|
|
31
|
+
loc_name: Optional[str] = typer.Option(None, "-loc", "--location-name", help="Location name for the output"),
|
|
32
|
+
):
|
|
33
|
+
"""Download weather data (NOAA station or reanalysis by coordinates).
|
|
34
|
+
|
|
35
|
+
NOAA station: noaaplotter download-data -o data/kotzebue.parquet -sid USW00026616 -start 1970-01-01 -end 2021-12-31
|
|
36
|
+
ERA5 (open_meteo): noaaplotter download-data -o data/potsdam.parquet --source open_meteo -lat 52.4 -lon 13.05 -start 1980-01-01 -end 2021-12-31
|
|
37
|
+
"""
|
|
38
|
+
src = source.lower()
|
|
39
|
+
|
|
40
|
+
if src in ("open_meteo", "cds"):
|
|
41
|
+
if latitude is None or longitude is None:
|
|
42
|
+
raise typer.BadParameter(f"--source {src} requires both -lat and -lon")
|
|
43
|
+
name = loc_name or f"{latitude:.2f},{longitude:.2f}"
|
|
44
|
+
df = get_source(src)(
|
|
45
|
+
latitude=latitude,
|
|
46
|
+
longitude=longitude,
|
|
47
|
+
start=start_date,
|
|
48
|
+
end=end_date,
|
|
49
|
+
name=name,
|
|
50
|
+
)
|
|
51
|
+
save_to_parquet(df, output_file)
|
|
52
|
+
typer.echo(f"Saved {df.shape[0]} rows ({name}) to {output_file}")
|
|
53
|
+
return
|
|
54
|
+
|
|
55
|
+
# NOAA path (default)
|
|
56
|
+
if not station_id:
|
|
57
|
+
raise typer.BadParameter("NOAA data requires -sid (station id)")
|
|
58
|
+
|
|
59
|
+
# token is optional: the NCEI service endpoint this hits is public. It is
|
|
60
|
+
# only forwarded if the user has one set (legacy/defensive), and a
|
|
61
|
+
# DeprecationWarning is raised if so.
|
|
62
|
+
api_token = get_noaa_token(token)
|
|
63
|
+
|
|
64
|
+
datatypes_list = [dt.strip() for dt in datatypes.split(",") if dt.strip()]
|
|
65
|
+
|
|
66
|
+
download_from_noaa(
|
|
67
|
+
output_file=output_file,
|
|
68
|
+
start_date=start_date,
|
|
69
|
+
end_date=end_date,
|
|
70
|
+
datatypes=datatypes_list,
|
|
71
|
+
noaa_api_token=api_token,
|
|
72
|
+
loc_name=loc_name,
|
|
73
|
+
station_id=station_id,
|
|
74
|
+
n_jobs=n_jobs,
|
|
75
|
+
)
|
|
76
|
+
typer.echo(f"Downloaded data for {station_id} ({start_date} .. {end_date}) to {output_file}")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _report(save_path, show_plot, engine):
|
|
80
|
+
if save_path:
|
|
81
|
+
typer.echo(f"Plot written to {save_path}")
|
|
82
|
+
elif show_plot:
|
|
83
|
+
typer.echo("Plot displayed (in-browser / GUI)")
|
|
84
|
+
else:
|
|
85
|
+
if engine == "plotly":
|
|
86
|
+
typer.echo("Figure created in memory - add -save_plot <x.html> to write it out")
|
|
87
|
+
else:
|
|
88
|
+
typer.echo("Figure created in memory - add -save_plot <x.png> to write it out")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@app.command("plot-daily")
|
|
92
|
+
def plot_daily(
|
|
93
|
+
infile: str = typer.Option(..., "-infile", "--input-file", help="Input file (parquet/csv) with climate data"),
|
|
94
|
+
start_date: str = typer.Option(..., "-start", "--start-date", help="Start date of plot (YYYY-MM-DD)"),
|
|
95
|
+
end_date: str = typer.Option(..., "-end", "--end-date", help="End date of plot (YYYY-MM-DD)"),
|
|
96
|
+
location: Optional[str] = typer.Option(None, "-loc", "--location", help="Location name, must be in data file"),
|
|
97
|
+
save_path: Optional[str] = typer.Option(None, "-save_plot", "--save-plot", help="File path for the plot (png, or html with --engine plotly)"),
|
|
98
|
+
t_range: Optional[Tuple[float, float]] = typer.Option(None, "-t_range", "--temperature-range", help="Temperature range (min, max), e.g. -45 25"),
|
|
99
|
+
p_range: Optional[float] = typer.Option(None, "-p_range", "--precipitation-range", help="Maximum precipitation value in the plot"),
|
|
100
|
+
s_range: Optional[float] = typer.Option(None, "-s_range", "--snow-range", help="Maximum snow accumulation value in the plot"),
|
|
101
|
+
snow_acc: bool = typer.Option(False, "--snow_acc", "--snow-accumulation", help="Show snow accumulation (useful for the winter season, e.g. July to June)"),
|
|
102
|
+
filtersize: int = typer.Option(7, "-filtersize", help="Smooth the climate temperature series by n days (default 7)"),
|
|
103
|
+
dpi: float = typer.Option(300.0, "--dpi", help="DPI for plot output (print quality; matches the Python API default)"),
|
|
104
|
+
show_plot: bool = typer.Option(False, "--plot", "--show-plot", help="Open the plot in a browser/GUI"),
|
|
105
|
+
figsize: Optional[Tuple[float, float]] = typer.Option(None, "-figsize", help="Figure size in inches, width height (e.g. 15 10 for 2 years)"),
|
|
106
|
+
title: Optional[str] = typer.Option(None, "-title", help="Plot title"),
|
|
107
|
+
engine: str = typer.Option("matplotlib", "--engine", help="Rendering engine: matplotlib (static) or plotly (interactive HTML)"),
|
|
108
|
+
full_series: bool = typer.Option(False, "--full-series", help="plotly only: include the ENTIRE observed record in the interactive plot; the initial view is still limited to the requested period (default: plot only the requested period, lightweight)"),
|
|
109
|
+
):
|
|
110
|
+
"""Create a daily temperature/precipitation plot vs. climate.
|
|
111
|
+
|
|
112
|
+
Example: noaaplotter plot-daily -infile data/kotzebue.parquet -start 1992-01-01 -end 1992-12-31 -t_range -45 25 -p_range 50 -save_plot figures/kotzebue_1992.png
|
|
113
|
+
"""
|
|
114
|
+
tmin, tmax = ("auto", "auto") if t_range is None else t_range
|
|
115
|
+
fsize = figsize if figsize is not None else (9, 6)
|
|
116
|
+
|
|
117
|
+
if engine not in ("matplotlib", "plotly"):
|
|
118
|
+
raise typer.BadParameter("engine must be 'matplotlib' or 'plotly'")
|
|
119
|
+
if not infile:
|
|
120
|
+
raise typer.BadParameter("-infile is required")
|
|
121
|
+
|
|
122
|
+
n = NOAAPlotter(infile, location=location, climate_filtersize=filtersize)
|
|
123
|
+
|
|
124
|
+
n.plot_weather_series(
|
|
125
|
+
start_date=start_date,
|
|
126
|
+
end_date=end_date,
|
|
127
|
+
show_snow_accumulation=snow_acc,
|
|
128
|
+
plot_extrema=True,
|
|
129
|
+
show_plot=show_plot,
|
|
130
|
+
save_path=save_path or False,
|
|
131
|
+
plot_tmin=tmin,
|
|
132
|
+
plot_tmax=tmax,
|
|
133
|
+
plot_pmax=p_range,
|
|
134
|
+
plot_snowmax=s_range,
|
|
135
|
+
dpi=dpi,
|
|
136
|
+
figsize=fsize,
|
|
137
|
+
title=title,
|
|
138
|
+
engine=engine,
|
|
139
|
+
full_series=full_series,
|
|
140
|
+
)
|
|
141
|
+
_report(save_path, show_plot, engine)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
@app.command("plot-monthly")
|
|
145
|
+
def plot_monthly(
|
|
146
|
+
infile: str = typer.Option(..., "-infile", "--input-file", help="Input file (parquet/csv) with climate data"),
|
|
147
|
+
start_date: str = typer.Option(..., "-start", "--start-date", help="Start date of plot (YYYY-MM-DD)"),
|
|
148
|
+
end_date: str = typer.Option(..., "-end", "--end-date", help="End date of plot (YYYY-MM-DD)"),
|
|
149
|
+
location: Optional[str] = typer.Option(None, "-loc", "--location", help="Location name, must be in data file"),
|
|
150
|
+
save_path: Optional[str] = typer.Option(None, "-save_plot", "--save-plot", help="File path for the plot (png, or html with --engine plotly)"),
|
|
151
|
+
information: str = typer.Option("Temperature", "-type", "--information", help="Attribute type: Temperature or Precipitation"),
|
|
152
|
+
trailing_mean: Optional[int] = typer.Option(None, "-trail", "--trailing-mean", help="Trailing/rolling mean in months (e.g. 12)"),
|
|
153
|
+
anomaly: bool = typer.Option(False, "-anomaly", help="Show anomaly from climate baseline"),
|
|
154
|
+
dpi: float = typer.Option(300.0, "--dpi", help="DPI for plot output (print quality; matches the Python API default)"),
|
|
155
|
+
show_plot: bool = typer.Option(False, "--plot", "--show-plot", help="Open the plot in a browser/GUI"),
|
|
156
|
+
figsize: Optional[Tuple[float, float]] = typer.Option(None, "-figsize", help="Figure size in inches, width height"),
|
|
157
|
+
engine: str = typer.Option("matplotlib", "--engine", help="Rendering engine: matplotlib (static) or plotly (interactive HTML)"),
|
|
158
|
+
):
|
|
159
|
+
"""Create a monthly temperature/precipitation bar chart.
|
|
160
|
+
|
|
161
|
+
Example: noaaplotter plot-monthly -infile data/kotzebue.parquet -start 1980-01-01 -end 2021-12-31 -type Temperature -trail 12 -anomaly -save_plot figures/kotzebue_t_anomaly.png
|
|
162
|
+
"""
|
|
163
|
+
if engine not in ("matplotlib", "plotly"):
|
|
164
|
+
raise typer.BadParameter("engine must be 'matplotlib' or 'plotly'")
|
|
165
|
+
if information not in ("Temperature", "Precipitation"):
|
|
166
|
+
raise typer.BadParameter("-type must be 'Temperature' or 'Precipitation'")
|
|
167
|
+
if not infile:
|
|
168
|
+
raise typer.BadParameter("-infile is required")
|
|
169
|
+
|
|
170
|
+
fsize = figsize if figsize is not None else (9, 4)
|
|
171
|
+
|
|
172
|
+
n = NOAAPlotter(infile, location=location)
|
|
173
|
+
|
|
174
|
+
n.plot_monthly_barchart(
|
|
175
|
+
start_date=start_date,
|
|
176
|
+
end_date=end_date,
|
|
177
|
+
information=information,
|
|
178
|
+
anomaly=anomaly,
|
|
179
|
+
trailing_mean=trailing_mean,
|
|
180
|
+
show_plot=show_plot,
|
|
181
|
+
dpi=dpi,
|
|
182
|
+
figsize=fsize,
|
|
183
|
+
save_path=save_path or False,
|
|
184
|
+
engine=engine,
|
|
185
|
+
)
|
|
186
|
+
_report(save_path, show_plot, engine)
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""Interactive (plotly) daily series figure.
|
|
2
|
+
|
|
3
|
+
Mirrors `NOAAPlotter.plot_weather_series`: temperature panel (observed vs
|
|
4
|
+
climatological mean +/- std with red/blue fill, no-data shading, record
|
|
5
|
+
markers) plus precipitation panel (bars, 7-day rolling sum, no-data shading,
|
|
6
|
+
optional cumulative snowfall on a secondary axis).
|
|
7
|
+
|
|
8
|
+
When `window=(start, end)` is given (the user's selected plotting period) the
|
|
9
|
+
figure carries the ENTIRE observed series and only the initial view is limited
|
|
10
|
+
to that window — users can zoom out manually to browse the full record.
|
|
11
|
+
When no window is given the old behaviour applies (the series shown is
|
|
12
|
+
exactly what is passed in).
|
|
13
|
+
"""
|
|
14
|
+
import numpy as np
|
|
15
|
+
import pandas as pd
|
|
16
|
+
import plotly.graph_objects as go
|
|
17
|
+
from plotly.subplots import make_subplots
|
|
18
|
+
|
|
19
|
+
C_HIGH = "#d6604d"
|
|
20
|
+
C_LOW = "#4393c3"
|
|
21
|
+
YEAR_BAND = "rgba(0,0,0,0.025)" # light grey per calendar year (even years white)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _clean(v):
|
|
25
|
+
"""Convert value to float or None if NaN."""
|
|
26
|
+
v = float(v)
|
|
27
|
+
return None if np.isnan(v) else v
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _grey_band(xs, top, bottom):
|
|
31
|
+
"""Closed light-grey polygon between two curves (no hover action)."""
|
|
32
|
+
xs = list(xs)
|
|
33
|
+
top_y = [_clean(v) for v in top]
|
|
34
|
+
bot_y = [_clean(v) for v in bottom]
|
|
35
|
+
return go.Scatter(x=xs + xs[::-1], y=top_y + bot_y[::-1],
|
|
36
|
+
fill="toself", fillcolor="rgba(190,190,190,0.18)",
|
|
37
|
+
line=dict(width=0), hoverinfo="skip",
|
|
38
|
+
showlegend=False)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _fill_band(xs, bottom, top, hexcolor, alpha, name=None, showlegend=False):
|
|
42
|
+
"""Closed polygon between two curves (NaNs break the band); optional legend entry."""
|
|
43
|
+
xs = list(xs)
|
|
44
|
+
bot_y = [_clean(v) for v in bottom]
|
|
45
|
+
top_y = [_clean(v) for v in top]
|
|
46
|
+
r, g, b = (int(hexcolor[i:i + 2], 16) for i in (1, 3, 5))
|
|
47
|
+
return go.Scatter(x=xs + xs[::-1], y=bot_y + top_y[::-1],
|
|
48
|
+
fill="toself", fillcolor=f"rgba({r},{g},{b},{alpha})",
|
|
49
|
+
line=dict(width=0), hoverinfo="skip",
|
|
50
|
+
name=name, showlegend=showlegend)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _add_year_bands(fig, dates, row):
|
|
54
|
+
"""Alternating light-grey / white background bands per calendar year.
|
|
55
|
+
|
|
56
|
+
Odd years get a very light grey band, even years stay white — same
|
|
57
|
+
convention as the monthly plots. ``add_shape`` with ``yref='paper'``
|
|
58
|
+
spans the full plot height of the given subplot row.
|
|
59
|
+
"""
|
|
60
|
+
years = sorted({d.year for d in dates})
|
|
61
|
+
axis = f"y{row}" if row != 1 else "y"
|
|
62
|
+
for year in years:
|
|
63
|
+
if year % 2 == 0:
|
|
64
|
+
continue # white: nothing to draw
|
|
65
|
+
fig.add_shape(
|
|
66
|
+
type="rect",
|
|
67
|
+
x0=f"{year}-01-01",
|
|
68
|
+
x1=f"{year}-12-31",
|
|
69
|
+
y0=0, y1=1,
|
|
70
|
+
yref=f"{axis} domain",
|
|
71
|
+
xref=f"x{row}" if row != 1 else "x",
|
|
72
|
+
fillcolor=YEAR_BAND,
|
|
73
|
+
line_width=0,
|
|
74
|
+
layer="below",
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def make_daily_figure(df_obs, x_dates, x_dates_short, y_clim, y_clim_hi, y_clim_lo,
|
|
79
|
+
ext_hi=None, ext_lo=None, snow_dates=None, snow_acc=None,
|
|
80
|
+
snow_tail=None, show_snow_accumulation=True,
|
|
81
|
+
plot_pmax=None, plot_snowmax=None, title=None,
|
|
82
|
+
figsize=(900, 600), window=None):
|
|
83
|
+
"""Build the interactive daily figure.
|
|
84
|
+
|
|
85
|
+
window : (start, end) timestamps, optional
|
|
86
|
+
Initial visible x-range. When set, the full observed series is shown
|
|
87
|
+
and only the initial view is clipped to this period.
|
|
88
|
+
"""
|
|
89
|
+
if x_dates_short is not None:
|
|
90
|
+
dates = list(x_dates_short["DATE"])
|
|
91
|
+
else:
|
|
92
|
+
dates = list(df_obs["DATE"])
|
|
93
|
+
xfull = list(x_dates["DATE"]) if x_dates is not None else dates
|
|
94
|
+
obs = np.asarray(df_obs["TMEAN"], dtype=float)
|
|
95
|
+
prcp = np.asarray(df_obs["PRCP"], dtype=float)
|
|
96
|
+
# Full-window climatology (drives the reference lines, so the x-axis still
|
|
97
|
+
# runs to the requested end date even when it lies in the future).
|
|
98
|
+
clim_full = np.asarray(y_clim, dtype=float)
|
|
99
|
+
clim_hi_full = np.asarray(y_clim_hi if y_clim_hi is not None else y_clim, dtype=float)
|
|
100
|
+
clim_lo_full = np.asarray(y_clim_lo if y_clim_lo is not None else y_clim, dtype=float)
|
|
101
|
+
# Climatology aligned to the OBSERVED span. The requested window may extend
|
|
102
|
+
# past the last available data (future end date); every trace derived from
|
|
103
|
+
# the observed series must line up with it — mirroring the static render,
|
|
104
|
+
# which fills against y_clim.loc[clim_locs_short].
|
|
105
|
+
if y_clim is not None:
|
|
106
|
+
clim = np.asarray(y_clim.reindex(df_obs["DATE"]), dtype=float)
|
|
107
|
+
clim_hi = np.asarray(y_clim_hi.reindex(df_obs["DATE"]), dtype=float)
|
|
108
|
+
clim_lo = np.asarray(y_clim_lo.reindex(df_obs["DATE"]), dtype=float)
|
|
109
|
+
else:
|
|
110
|
+
clim = clim_hi = clim_lo = np.full(len(df_obs), np.nan)
|
|
111
|
+
|
|
112
|
+
# 7-day rolling sum of precipitation (computed early: the precipitation
|
|
113
|
+
# y-range must include it so the full line is visible initially)
|
|
114
|
+
prcp_rolling = pd.Series(prcp).rolling(window=7, min_periods=1, center=True).sum()
|
|
115
|
+
|
|
116
|
+
fig = make_subplots(rows=2, cols=1, shared_xaxes=True,
|
|
117
|
+
row_heights=[0.6, 0.4], vertical_spacing=0.07)
|
|
118
|
+
|
|
119
|
+
# --- calendar-year background bands (light grey / white), both panels
|
|
120
|
+
for row in (1, 2):
|
|
121
|
+
_add_year_bands(fig, dates, row)
|
|
122
|
+
|
|
123
|
+
# --- temperature: soft light-grey climatological +/- sigma envelope (no hover)
|
|
124
|
+
fig.add_trace(_grey_band(dates, clim_hi, clim_lo), 1, 1)
|
|
125
|
+
# --- temperature: anomaly fills between the observed line and the climate
|
|
126
|
+
# baseline (mirrors the static render): light within +/- 1 std, darker
|
|
127
|
+
# once the observation exceeds the envelope (no hover action)
|
|
128
|
+
# within 1 std: mean -> obs (or mean -> sigma edge if obs is outside the band)
|
|
129
|
+
upper_in = np.fmax(clim, np.fmin(obs, clim_hi))
|
|
130
|
+
lower_in = np.fmin(clim, np.fmax(obs, clim_lo))
|
|
131
|
+
# beyond 1 std: ONLY in the region actually exceeded by the observation
|
|
132
|
+
upper_out = np.fmax(obs, clim_hi)
|
|
133
|
+
lower_out = np.fmin(obs, clim_lo)
|
|
134
|
+
fig.add_trace(_fill_band(dates, clim, upper_in, C_HIGH, 0.3,
|
|
135
|
+
name="Above average Temperature",
|
|
136
|
+
showlegend=True), 1, 1)
|
|
137
|
+
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)
|
|
140
|
+
fig.add_trace(_fill_band(dates, lower_in, clim, C_LOW, 0.3,
|
|
141
|
+
name="Below average Temperature",
|
|
142
|
+
showlegend=True), 1, 1)
|
|
143
|
+
fig.add_trace(_fill_band(dates, lower_out, clim_lo, C_LOW, 0.7,
|
|
144
|
+
name="Below average Temperature (> 1 std)",
|
|
145
|
+
showlegend=True), 1, 1)
|
|
146
|
+
# --- reference lines + observed (visual weight matched to the static render:
|
|
147
|
+
# normals lw=2 @ 50% alpha, observed lw=1.2 @ 40% alpha,
|
|
148
|
+
# sigma edges lw=1 @ 40% alpha). Hover values truncated to 2 decimals.
|
|
149
|
+
fig.add_trace(go.Scatter(x=xfull, y=clim_full, name="Climatological Mean",
|
|
150
|
+
line=dict(color="rgba(0,0,0,0.5)", width=2),
|
|
151
|
+
hovertemplate="Climatology: %{y:.2f} °C<extra></extra>"), 1, 1)
|
|
152
|
+
fig.add_trace(go.Scatter(x=xfull, y=clim_hi_full, name="Std of Climatological Mean",
|
|
153
|
+
line=dict(color="rgba(0,0,0,0.4)", width=1, dash="dot"),
|
|
154
|
+
hovertemplate="Upper 1σ: %{y:.2f} °C<extra></extra>"), 1, 1)
|
|
155
|
+
fig.add_trace(go.Scatter(x=xfull, y=clim_lo_full, showlegend=False,
|
|
156
|
+
line=dict(color="rgba(0,0,0,0.4)", width=1, dash="dot"),
|
|
157
|
+
hovertemplate="Lower 1σ: %{y:.2f} °C<extra></extra>"), 1, 1)
|
|
158
|
+
fig.add_trace(go.Scatter(x=dates, y=list(pd.Series(obs).where(pd.notna(obs))),
|
|
159
|
+
name="Observed Temperatures",
|
|
160
|
+
line=dict(color="rgba(0,0,0,0.4)", width=1.2),
|
|
161
|
+
hovertemplate="Observed: %{y:.2f} °C<extra></extra>"), 1, 1)
|
|
162
|
+
|
|
163
|
+
# --- temperature: y-range + no-data shading + zero line.
|
|
164
|
+
# The range covers EVERYTHING visible (observed series AND climatology)
|
|
165
|
+
# so no value is clipped in the initial view.
|
|
166
|
+
span_hi = float(np.nanmax(np.concatenate([obs, clim_hi_full])))
|
|
167
|
+
span_lo = float(np.nanmin(np.concatenate([obs, clim_lo_full])))
|
|
168
|
+
fig.update_yaxes(range=[span_lo, span_hi], title="Temperature in °C",
|
|
169
|
+
row=1, col=1)
|
|
170
|
+
nan_t = [d for d, v in zip(dates, obs) if v is None or pd.isna(v)]
|
|
171
|
+
if nan_t:
|
|
172
|
+
fig.add_trace(go.Bar(x=nan_t, y=[span_hi - span_lo] * len(nan_t),
|
|
173
|
+
base=span_lo, width=1,
|
|
174
|
+
marker_color="rgba(0,0,0,0.2)",
|
|
175
|
+
name="No Data", showlegend=True), 1, 1)
|
|
176
|
+
fig.add_hline(y=0, line=dict(color="rgba(0,0,0,0.5)", dash="dash"), row=1, col=1)
|
|
177
|
+
|
|
178
|
+
# --- temperature: record extremes
|
|
179
|
+
if ext_hi is not None and len(ext_hi[0]) > 0:
|
|
180
|
+
fig.add_trace(go.Scatter(x=list(ext_hi[0]), y=list(ext_hi[1]),
|
|
181
|
+
mode="markers", name="Record High on Date",
|
|
182
|
+
marker=dict(symbol="x", size=8, color=C_HIGH),
|
|
183
|
+
hovertemplate="Record high: %{y:.2f} °C<extra></extra>"), 1, 1)
|
|
184
|
+
if ext_lo is not None and len(ext_lo[0]) > 0:
|
|
185
|
+
fig.add_trace(go.Scatter(x=list(ext_lo[0]), y=list(ext_lo[1]),
|
|
186
|
+
mode="markers", name="Record Low on Date",
|
|
187
|
+
marker=dict(symbol="x", size=8, color=C_LOW),
|
|
188
|
+
hovertemplate="Record low: %{y:.2f} °C<extra></extra>"), 1, 1)
|
|
189
|
+
|
|
190
|
+
# --- precipitation: bars + no-data shading.
|
|
191
|
+
# y-range includes the 7-day rolling sum (often higher than the max daily
|
|
192
|
+
# bar) so the full rolling line is visible in the initial view.
|
|
193
|
+
rolling_max = float(np.nanmax(prcp_rolling.to_numpy()))
|
|
194
|
+
rolling_max = rolling_max if np.isfinite(rolling_max) else 0.0
|
|
195
|
+
if plot_pmax is not None:
|
|
196
|
+
prcp_top = float(plot_pmax)
|
|
197
|
+
else:
|
|
198
|
+
base = float(np.nanmax(prcp)) if np.size(prcp) else 0.0
|
|
199
|
+
prcp_top = max(base * 1.15, rolling_max * 1.15, 1.0)
|
|
200
|
+
fig.update_yaxes(range=[0, prcp_top], title="Precipitation in mm", row=2, col=1)
|
|
201
|
+
fig.add_trace(go.Bar(x=dates, y=list(pd.Series(prcp).where(pd.notna(prcp))),
|
|
202
|
+
name="Precipitation", marker_color=C_LOW,
|
|
203
|
+
hovertemplate="Precipitation: %{y:.2f} mm<extra></extra>"), 2, 1)
|
|
204
|
+
nan_p = [d for d, v in zip(dates, prcp) if v is None or pd.isna(v)]
|
|
205
|
+
if nan_p:
|
|
206
|
+
fig.add_trace(go.Bar(x=nan_p, y=[prcp_top] * len(nan_p), base=0, width=1,
|
|
207
|
+
marker_color="rgba(0,0,0,0.2)",
|
|
208
|
+
name="No Data", showlegend=True), 2, 1)
|
|
209
|
+
|
|
210
|
+
# --- rolling 7-day precipitation sum
|
|
211
|
+
# Convert to list for Plotly
|
|
212
|
+
prcp_rolling_list = list(prcp_rolling.where(pd.notna(prcp_rolling)))
|
|
213
|
+
fig.add_trace(go.Scatter(x=dates, y=prcp_rolling_list,
|
|
214
|
+
name="7-Day Rolling Sum of Precipitation",
|
|
215
|
+
line=dict(color="rgba(30,144,255,0.7)", width=2),
|
|
216
|
+
hovertemplate="7-day Rolling Sum: %{y:.2f} mm<extra></extra>"), 2, 1)
|
|
217
|
+
|
|
218
|
+
# --- snowfall accumulation: its OWN secondary axis on the precipitation row.
|
|
219
|
+
# NOTE: add_trace() WITHOUT row/col on purpose — subplot row/col pinning would
|
|
220
|
+
# force the trace onto the precipitation axis (y2) and hide the rain bars.
|
|
221
|
+
if show_snow_accumulation and snow_dates is not None:
|
|
222
|
+
snow_max = float(np.nanmax(snow_acc) / 10) if np.nanmax(snow_acc) > 0 else 1.0
|
|
223
|
+
snow_top = plot_snowmax if plot_snowmax is not None else snow_max * 1.1
|
|
224
|
+
fig.add_trace(go.Scatter(x=list(snow_dates),
|
|
225
|
+
y=[v / 10 for v in snow_acc],
|
|
226
|
+
name="Cumulative Snowfall",
|
|
227
|
+
line=dict(width=0),
|
|
228
|
+
fillcolor="rgba(0,0,0,0.2)",
|
|
229
|
+
fill="tozeroy", yaxis="y3",
|
|
230
|
+
hovertemplate="Snow: %{y:.2f} cm<extra></extra>"))
|
|
231
|
+
fig.update_layout(yaxis3=dict(title="Cumulative Snowfall in cm", side="right",
|
|
232
|
+
overlaying="y2", anchor="free", position=1.0,
|
|
233
|
+
range=[0, snow_top]))
|
|
234
|
+
if snow_tail is not None:
|
|
235
|
+
fig.add_trace(go.Scatter(x=list(snow_tail[0]), y=list(snow_tail[1]),
|
|
236
|
+
opacity=0.2,
|
|
237
|
+
line=dict(color="black", width=1, dash="dash"),
|
|
238
|
+
showlegend=False, yaxis="y3"))
|
|
239
|
+
|
|
240
|
+
layout = dict(height=figsize[1], width=figsize[0],
|
|
241
|
+
template="plotly_white", hovermode="x unified",
|
|
242
|
+
showlegend=True,
|
|
243
|
+
legend=dict(orientation="h", yanchor="bottom", y=1.02,
|
|
244
|
+
xanchor="left", x=0),
|
|
245
|
+
margin=dict(l=40, r=40, t=50 if title else 40, b=30),
|
|
246
|
+
title=dict(text=title, y=0.98) if title else None,
|
|
247
|
+
xaxis_rangeslider_visible=False,
|
|
248
|
+
xaxis_title="Date")
|
|
249
|
+
# --- initial x-view (window = user-selected period).
|
|
250
|
+
# NOTE: with shared_xaxes the visible master axis is x2 (xaxis "matches"
|
|
251
|
+
# it and is hidden), so the initial range must be applied to BOTH.
|
|
252
|
+
if window is not None:
|
|
253
|
+
d0 = pd.Timestamp(window[0]).strftime("%Y-%m-%d")
|
|
254
|
+
d1 = pd.Timestamp(window[1]).strftime("%Y-%m-%d")
|
|
255
|
+
layout["xaxis_range"] = [d0, d1]
|
|
256
|
+
layout["xaxis2_range"] = [d0, d1]
|
|
257
|
+
fig.update_layout(**layout)
|
|
258
|
+
return fig
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Interactive (plotly) monthly barchart figure.
|
|
2
|
+
|
|
3
|
+
Mirrors `NOAAPlotter.plot_monthly_barchart`: monthly bars coloured by sign
|
|
4
|
+
(above/below reference), optional trailing-mean line, and a zero line.
|
|
5
|
+
"""
|
|
6
|
+
import plotly.graph_objects as go
|
|
7
|
+
|
|
8
|
+
C_HIGH = "#d6604d"
|
|
9
|
+
C_LOW = "#4393c3"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def make_monthly_figure(data, plot_kwargs, trailing_mean=None, title=None,
|
|
13
|
+
figsize=(900, 420)):
|
|
14
|
+
"""Build the interactive monthly figure.
|
|
15
|
+
|
|
16
|
+
data : DataFrame with DATE (datetime), the value column, and optionally
|
|
17
|
+
trailing_values. plot_kwargs : from setup_monthly_plot_props().
|
|
18
|
+
"""
|
|
19
|
+
value_col = plot_kwargs["value_column"]
|
|
20
|
+
value = data[value_col]
|
|
21
|
+
d_low = data[value < 0]
|
|
22
|
+
d_high = data[value >= 0]
|
|
23
|
+
fig = go.Figure()
|
|
24
|
+
|
|
25
|
+
fig.add_trace(go.Bar(x=d_low["DATE"], y=d_low[value_col],
|
|
26
|
+
name=plot_kwargs.get("legend_label_below") or "Below",
|
|
27
|
+
marker=dict(color=plot_kwargs["fc_low"],
|
|
28
|
+
line=dict(width=0.5, color="white")),
|
|
29
|
+
opacity=0.92))
|
|
30
|
+
fig.add_trace(go.Bar(x=d_high["DATE"], y=d_high[value_col],
|
|
31
|
+
name=plot_kwargs.get("legend_label_above") or "Above",
|
|
32
|
+
marker=dict(color=plot_kwargs["fc_high"],
|
|
33
|
+
line=dict(width=0.5, color="white")),
|
|
34
|
+
opacity=0.92))
|
|
35
|
+
|
|
36
|
+
if trailing_mean and "trailing_values" in data.columns:
|
|
37
|
+
fig.add_trace(go.Scatter(x=data["DATE"], y=data["trailing_values"],
|
|
38
|
+
name=f"Trailing mean: {trailing_mean} months",
|
|
39
|
+
mode="lines", line=dict(color="black", width=1.5)))
|
|
40
|
+
|
|
41
|
+
fig.update_yaxes(title_text=plot_kwargs["y_label"])
|
|
42
|
+
fig.update_xaxes(title_text="Date")
|
|
43
|
+
fig.add_hline(y=0, line_color="rgba(0,0,0,0.5)", line_dash="dash")
|
|
44
|
+
|
|
45
|
+
fig.update_layout(height=figsize[1], width=figsize[0], template="plotly_white",
|
|
46
|
+
hovermode="x", showlegend=True,
|
|
47
|
+
legend=dict(orientation="h", yanchor="bottom", y=1.02,
|
|
48
|
+
xanchor="left", x=0),
|
|
49
|
+
margin=dict(l=40, r=40, t=50, b=40),
|
|
50
|
+
title=title or plot_kwargs["title"])
|
|
51
|
+
return fig
|