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.
@@ -0,0 +1,726 @@
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ ########################
5
+ # Credits here
6
+ # author: Ingmar Nitze, Alfred Wegener Institute for Polar and Marine Research
7
+ # contact: ingmar.nitze@awi.de
8
+ # version: 2021-09-06
9
+
10
+ import numpy as np
11
+ from matplotlib import dates
12
+
13
+ ########################
14
+ from matplotlib import pyplot as plt
15
+
16
+ from noaaplotter.utils.dataset import NOAAPlotterDailyClimateDataset as DS_daily
17
+ from noaaplotter.utils.dataset import NOAAPlotterDailySummariesDataset as Dataset
18
+ from noaaplotter.utils.dataset import NOAAPlotterMonthlyClimateDataset as DS_monthly
19
+ from noaaplotter.utils.plot_utils import *
20
+ from noaaplotter.utils.utils import *
21
+
22
+ pd.plotting.register_matplotlib_converters()
23
+ numeric_only = True
24
+
25
+
26
+ class NOAAPlotter(object):
27
+ """
28
+ This class/module creates nice plots of observed weather data from NOAA
29
+ """
30
+
31
+ def __init__(
32
+ self,
33
+ input_filepath=None,
34
+ location=None,
35
+ remove_feb29=False,
36
+ climate_start=dt.datetime(1981, 1, 1),
37
+ climate_end=dt.datetime(2010, 12, 31),
38
+ climate_filtersize=7,
39
+ ):
40
+ """
41
+
42
+ :param input_filepath: path to input file
43
+ :type input_filepath: str
44
+ :param location: name of location
45
+ :type location: str, optional
46
+ :param remove_feb29:
47
+ :type remove_feb29: bool, optional
48
+ :param climate_start: start date of climate period, defaults to 01-01-1981
49
+ :type climate_start: datetime, optional
50
+ :param climate_end: start date of climate period, defaults to 31-12-2010
51
+ :type climate_end: datetime, optional
52
+ """
53
+ self.input_filepath = input_filepath
54
+ self.location = location
55
+ self.climate_start = climate_start
56
+ self.climate_end = climate_end
57
+ self.remove_feb29 = remove_feb29
58
+ self.dataset = Dataset(
59
+ input_filepath, location=location, remove_feb29=remove_feb29
60
+ )
61
+
62
+ # TODO: move to respective functions?
63
+ self.df_clim_ = DS_daily(self.dataset, filtersize=climate_filtersize)
64
+ #
65
+
66
+ def _make_short_dateseries(self, start_date, end_date):
67
+ x_dates = pd.DataFrame()
68
+ x_dates["DATE"] = pd.date_range(start=start_date, end=end_date)
69
+ x_dates["DATE_MD"] = x_dates["DATE"].dt.strftime("%m-%d")
70
+ # TODO: Filter Feb29
71
+ if self.dataset.data["DATE"].max() >= end_date:
72
+ x_dates_short = x_dates.set_index("DATE", drop=False).loc[
73
+ pd.date_range(start=start_date, end=end_date)
74
+ ]
75
+ else:
76
+ x_dates_short = x_dates.set_index("DATE", drop=False).loc[
77
+ pd.date_range(start=start_date, end=self.dataset.data["DATE"].max())
78
+ ]
79
+
80
+ return x_dates, x_dates_short
81
+
82
+ def plot_weather_series(
83
+ self,
84
+ start_date,
85
+ end_date,
86
+ plot_tmax="auto",
87
+ plot_tmin="auto",
88
+ plot_pmax="auto",
89
+ plot_snowmax="auto",
90
+ plot_extrema=True,
91
+ show_plot=True,
92
+ show_snow_accumulation=False,
93
+ save_path=False,
94
+ figsize=(9, 6),
95
+ legend_fontsize="x-small",
96
+ dpi=300,
97
+ title=None,
98
+ return_plot=False,
99
+ engine="matplotlib",
100
+ full_series=False,
101
+ ):
102
+ """
103
+ Plotting Function to show observed vs climate temperatures and snowfall
104
+ :param engine: "matplotlib" (static, default) or "plotly" (interactive, returned as a plotly Figure)
105
+ :type engine: str
106
+ :param full_series: plotly only — carry the ENTIRE observed record in the figure
107
+ and only limit the initial view to the requested window (default: plot only
108
+ the requested window, lightweight)
109
+ :type full_series: bool
110
+ :param dpi:
111
+ :param legend_fontsize:
112
+ :param figsize:
113
+ :param start_date: start date of plot
114
+ :type start_date: datetime, str
115
+ :param end_date: end date of plot
116
+ :type end_date: datetime, str
117
+ :param plot_tmax:
118
+ :type plot_tmax: int, float, str
119
+ :param plot_tmin:
120
+ :type plot_tmin: int, float, str
121
+ :param plot_pmax:
122
+ :type plot_pmax: int, float, str
123
+ :param plot_snowmax:
124
+ :type plot_snowmax: int, float, str
125
+ :param plot_extrema:
126
+ :type plot_extrema:
127
+ :param show_plot:
128
+ :type show_plot:
129
+ :param show_snow_accumulation: show the cumulative snowfall axis (opt-in;
130
+ defaults to ``False`` to match the CLI's ``--snow_acc`` default).
131
+ :type show_snow_accumulation: bool
132
+ :param save_path:
133
+ :type save_path:
134
+ :return:
135
+ """
136
+ import warnings
137
+
138
+ start_date = parse_dates(start_date)
139
+ end_date = parse_dates(end_date)
140
+ x_dates, x_dates_short = self._make_short_dateseries(start_date, end_date)
141
+
142
+ df_clim = self.df_clim_.data.loc[x_dates["DATE_MD"]]
143
+
144
+ df_clim["DATE"] = x_dates["DATE"].values
145
+ df_clim = df_clim.set_index("DATE", drop=False)
146
+
147
+ # The requested window may extend beyond the last available data date,
148
+ # and the underlying record may have internal gaps (missing observation
149
+ # days). Select only dates that actually exist so no KeyError is
150
+ # raised; missing days simply appear as gaps in the plotted line.
151
+ data = self.dataset.data
152
+ avail_dates = set(pd.to_datetime(data["DATE"]))
153
+ data_first = pd.Timestamp(data["DATE"].min())
154
+ data_last = pd.Timestamp(data["DATE"].max())
155
+
156
+ # x_dates_short has a DatetimeIndex (DATE) plus a DATE column; filter
157
+ # it down to the dates that actually exist in the data file so the
158
+ # observed-panel x-axis and the climate-alignment below use the same
159
+ # (shorter) set of dates. Keeps the DatetimeIndex for later .loc[]
160
+ # use (e.g. `x_dates_short.loc[:last_snow_date, ...]`).
161
+ selected = [d for d in x_dates_short.index if d in avail_dates]
162
+ if not selected:
163
+ raise ValueError(
164
+ f"No data available for the requested window "
165
+ f"({start_date.date()} .. {end_date.date()}). "
166
+ f"Data file covers {data_first.date()} to {data_last.date()}."
167
+ )
168
+ df_obs = data.set_index("DATE", drop=False).loc[selected]
169
+ x_dates_short = x_dates_short.loc[selected]
170
+
171
+ # Warn when the user asked for a range wider than what the data file
172
+ # actually covers, so an accidental typo (or a future end date) is
173
+ # visible instead of silently clipped.
174
+ if end_date > data_last:
175
+ warnings.warn(
176
+ f"end date {end_date.date()} is beyond the last available "
177
+ f"data date {data_last.date()}; plot stops at the last available date.",
178
+ stacklevel=2,
179
+ )
180
+ if start_date < data_first:
181
+ warnings.warn(
182
+ f"start date {start_date.date()} is before the first available "
183
+ f"data date {data_first.date()}; plot starts at the first available date.",
184
+ stacklevel=2,
185
+ )
186
+
187
+ clim_locs_short = x_dates_short[
188
+ "DATE"
189
+ ] # short series for incomplete years (actual data)
190
+
191
+ # get mean and mean+-standard deviation of daily mean temperatures of climate series
192
+ y_clim = df_clim["tmean_doy_mean"]
193
+ y_clim_std_hi = df_clim[["tmean_doy_mean", "tmean_doy_std"]].sum(axis=1)
194
+ y_clim_std_lo = df_clim["tmean_doy_mean"] - df_clim["tmean_doy_std"]
195
+
196
+ # Prepare data for filled plot areas
197
+ t_above = np.vstack(
198
+ [df_obs["TMEAN"].values, y_clim.loc[clim_locs_short].values]
199
+ ).max(axis=0)
200
+ t_above_std = np.vstack(
201
+ [df_obs["TMEAN"].values, y_clim_std_hi.loc[clim_locs_short].values]
202
+ ).max(axis=0)
203
+ t_below = np.vstack(
204
+ [df_obs["TMEAN"].values, y_clim.loc[clim_locs_short].values]
205
+ ).min(axis=0)
206
+ t_below_std = np.vstack(
207
+ [df_obs["TMEAN"].values, y_clim_std_lo.loc[clim_locs_short].values]
208
+ ).min(axis=0)
209
+
210
+ # Calculate the date of last snowfall and cumulative sum of snowfall
211
+ snow_requested = show_snow_accumulation
212
+ if not show_snow_accumulation:
213
+ None
214
+ elif (show_snow_accumulation) and ("SNOW" in df_obs.columns):
215
+ snow_pos = df_obs[df_obs["SNOW"] > 0]
216
+ if len(snow_pos) > 0:
217
+ last_snow_date = snow_pos.iloc[-1]["DATE"]
218
+ snow_acc = np.cumsum(df_obs["SNOW"])
219
+ else:
220
+ # no snowfall in the plotted window: skip the snow overlay
221
+ # (previously crashed on .iloc[-1] of an empty selection)
222
+ show_snow_accumulation = False
223
+ elif "SNOW" not in df_obs.columns:
224
+ show_snow_accumulation = False
225
+ raise Warning("No snow information available")
226
+
227
+ # ----- plotly engine: interactive figure -----
228
+ # Default: plot ONLY the requested window (lightweight). With
229
+ # full_series=True the figure carries the ENTIRE observed record and
230
+ # only the initial view is limited to the requested period.
231
+ if engine == "plotly":
232
+ from noaaplotter.figures import make_daily_figure
233
+
234
+ if not full_series:
235
+ # Lightweight: plot ONLY the requested window. All series are
236
+ # aligned to the dates that actually exist in the window.
237
+ src_df = df_obs
238
+ src_x = x_dates_short
239
+
240
+ # Climatology aligned to the windowed dates
241
+ y_clim_w = y_clim.reindex(df_obs["DATE"])
242
+ y_clim_hi_w = y_clim_std_hi.reindex(df_obs["DATE"])
243
+ y_clim_lo_w = y_clim_std_lo.reindex(df_obs["DATE"])
244
+
245
+ # Record extremes: analysis over the ENTIRE record (per
246
+ # month-day), then cropped to the plotted window — exactly
247
+ # like the static render (groupby on the full dataset).
248
+ ext_hi = ext_lo = None
249
+ if plot_extrema:
250
+ tmax = self.dataset.data.groupby("DATE_MD").max(numeric_only=numeric_only)["TMEAN"]
251
+ tmin = self.dataset.data.groupby("DATE_MD").min(numeric_only=numeric_only)["TMEAN"]
252
+ local_obs = src_df[["DATE", "DATE_MD", "TMEAN"]].set_index(
253
+ "DATE_MD", drop=False)
254
+ local_max = tmax.loc[local_obs.index] == local_obs["TMEAN"]
255
+ local_min = tmin.loc[local_obs.index] == local_obs["TMEAN"]
256
+ ext_hi = (
257
+ local_obs[local_max]["DATE"].values,
258
+ local_obs[local_max]["TMEAN"].values,
259
+ )
260
+ ext_lo = (
261
+ local_obs[local_min]["DATE"].values,
262
+ local_obs[local_min]["TMEAN"].values,
263
+ )
264
+
265
+ # Snow accumulation over the window (only when requested AND
266
+ # the window contains snowfall)
267
+ snow_dates = snow_acc_w = snow_tail = None
268
+ has_snow = bool(snow_requested and "SNOW" in src_df.columns
269
+ and (src_df["SNOW"] > 0).any())
270
+ if has_snow:
271
+ snow_acc_w = np.cumsum(src_df["SNOW"].to_numpy(dtype=float))
272
+ pos = int((src_df["DATE"] <= src_df.loc[src_df["SNOW"] > 0, "DATE"].iloc[-1]).sum())
273
+ snow_dates = src_df.iloc[:pos]["DATE"].values
274
+ snow_tail = (src_df.iloc[pos:]["DATE"].values,
275
+ (snow_acc_w[pos:] / 10))
276
+
277
+ fig_pl = make_daily_figure(
278
+ src_df, src_x, None,
279
+ y_clim_w, y_clim_hi_w, y_clim_lo_w,
280
+ ext_hi=ext_hi, ext_lo=ext_lo,
281
+ snow_dates=snow_dates,
282
+ snow_acc=snow_acc_w,
283
+ snow_tail=snow_tail,
284
+ show_snow_accumulation=has_snow,
285
+ plot_pmax=plot_pmax if isinstance(plot_pmax, (int, float)) else None,
286
+ plot_snowmax=plot_snowmax if isinstance(plot_snowmax, (int, float)) else None,
287
+ title=title,
288
+ figsize=(int(figsize[0] * 100), int(figsize[1] * 100)),
289
+ window=None,
290
+ )
291
+ else:
292
+ # Full-window observed series (all dates actually available)
293
+ src_df = self.dataset.data.sort_values("DATE")
294
+ src_x = pd.DataFrame({
295
+ "DATE": src_df["DATE"].values,
296
+ "DATE_MD": src_df["DATE"].dt.strftime("%m-%d").values,
297
+ }, index=src_df.index)
298
+
299
+ # Climatology over the full observed window
300
+ clim_df_all = self.df_clim_.data.loc[src_x["DATE_MD"]].copy()
301
+ clim_df_all["DATE"] = src_x["DATE"].values
302
+ clim_df_all = clim_df_all.set_index("DATE", drop=False)
303
+ y_clim_w = clim_df_all["tmean_doy_mean"]
304
+ y_clim_hi_w = clim_df_all[["tmean_doy_mean", "tmean_doy_std"]].sum(axis=1)
305
+ y_clim_lo_w = clim_df_all["tmean_doy_mean"] - clim_df_all["tmean_doy_std"]
306
+
307
+ # Record extremes over the full window (per month-day)
308
+ ext_hi = ext_lo = None
309
+ if plot_extrema:
310
+ tmax = src_df.groupby("DATE_MD").max(numeric_only=numeric_only)["TMEAN"]
311
+ tmin = src_df.groupby("DATE_MD").min(numeric_only=numeric_only)["TMEAN"]
312
+ local_obs = src_df[["DATE", "DATE_MD", "TMEAN"]].set_index(
313
+ "DATE_MD", drop=False)
314
+ local_max = tmax.loc[local_obs.index] == local_obs["TMEAN"]
315
+ local_min = tmin.loc[local_obs.index] == local_obs["TMEAN"]
316
+ ext_hi = (
317
+ local_obs[local_max]["DATE"].values,
318
+ local_obs[local_max]["TMEAN"].values,
319
+ )
320
+ ext_lo = (
321
+ local_obs[local_min]["DATE"].values,
322
+ local_obs[local_min]["TMEAN"].values,
323
+ )
324
+
325
+ # Snow accumulation over the full window
326
+ snow_dates = snow_acc_w = snow_tail = None
327
+ has_snow = bool(snow_requested and "SNOW" in src_df.columns
328
+ and (src_df["SNOW"] > 0).any())
329
+ if has_snow:
330
+ snow_acc_w = np.cumsum(src_df["SNOW"].to_numpy(dtype=float))
331
+ pos = int((src_df["DATE"] <= src_df.loc[src_df["SNOW"] > 0, "DATE"].iloc[-1]).sum())
332
+ snow_dates = src_df.iloc[:pos]["DATE"].values
333
+ snow_tail = (src_df.iloc[pos:]["DATE"].values,
334
+ (snow_acc_w[pos:] / 10))
335
+
336
+ fig_pl = make_daily_figure(
337
+ src_df, src_x, None,
338
+ y_clim_w, y_clim_hi_w, y_clim_lo_w,
339
+ ext_hi=ext_hi, ext_lo=ext_lo,
340
+ snow_dates=snow_dates,
341
+ snow_acc=snow_acc_w,
342
+ snow_tail=snow_tail,
343
+ show_snow_accumulation=has_snow,
344
+ plot_pmax=plot_pmax if isinstance(plot_pmax, (int, float)) else None,
345
+ plot_snowmax=plot_snowmax if isinstance(plot_snowmax, (int, float)) else None,
346
+ title=title,
347
+ figsize=(int(figsize[0] * 100), int(figsize[1] * 100)),
348
+ window=(pd.Timestamp(start_date), pd.Timestamp(end_date)),
349
+ )
350
+ if save_path:
351
+ fig_pl.write_html(
352
+ save_path if str(save_path).endswith(".html")
353
+ else str(save_path) + ".html"
354
+ )
355
+ return fig_pl
356
+
357
+ # ----- matplotlib rendering below -----
358
+ fig = plt.figure(figsize=figsize, dpi=dpi)
359
+ ax_t = fig.add_subplot(211)
360
+ ax_p = fig.add_subplot(212, sharex=ax_t)
361
+
362
+ # climate series (red line)
363
+ (cm,) = ax_t.plot(x_dates["DATE"].values, y_clim.values, c="k", alpha=0.5, lw=2)
364
+ (cm_hi,) = ax_t.plot(
365
+ x_dates["DATE"].values,
366
+ y_clim_std_hi.values,
367
+ c="r",
368
+ ls="--",
369
+ alpha=0.4,
370
+ lw=1,
371
+ )
372
+ (cm_low,) = ax_t.plot(
373
+ x_dates["DATE"].values,
374
+ y_clim_std_lo.values,
375
+ c="r",
376
+ ls="--",
377
+ alpha=0.4,
378
+ lw=1,
379
+ )
380
+
381
+ # observed series (grey line)
382
+ (fb,) = ax_t.plot(
383
+ x_dates_short["DATE"].values,
384
+ df_obs["TMEAN"].values,
385
+ c="k",
386
+ alpha=0.4,
387
+ lw=1.2,
388
+ )
389
+
390
+ # difference of observed and climate (grey area)
391
+ fill_r = ax_t.fill_between(
392
+ x_dates_short["DATE"].values,
393
+ y1=t_above,
394
+ y2=y_clim.loc[clim_locs_short].values,
395
+ facecolor="#d6604d",
396
+ alpha=0.5,
397
+ )
398
+ fill_rr = ax_t.fill_between(
399
+ x_dates_short["DATE"].values,
400
+ y1=t_above_std,
401
+ y2=y_clim_std_hi.loc[clim_locs_short].values,
402
+ facecolor="#d6604d",
403
+ alpha=0.7,
404
+ )
405
+ fill_b = ax_t.fill_between(
406
+ x_dates_short["DATE"].values,
407
+ y1=y_clim.loc[clim_locs_short].values,
408
+ y2=t_below,
409
+ facecolor="#4393c3",
410
+ alpha=0.5,
411
+ )
412
+ fill_bb = ax_t.fill_between(
413
+ x_dates_short["DATE"].values,
414
+ y1=y_clim_std_lo.loc[clim_locs_short].values,
415
+ y2=t_below_std,
416
+ facecolor="#4393c3",
417
+ alpha=0.7,
418
+ )
419
+
420
+ if plot_extrema:
421
+ tmax = self.dataset.data.groupby("DATE_MD").max(numeric_only=numeric_only)[
422
+ "TMEAN"
423
+ ]
424
+ tmin = self.dataset.data.groupby("DATE_MD").min(numeric_only=numeric_only)[
425
+ "TMEAN"
426
+ ]
427
+ local_obs = df_obs[["DATE", "DATE_MD", "TMEAN"]].set_index(
428
+ "DATE_MD", drop=False
429
+ )
430
+ idx = local_obs.index
431
+ local_max = tmax.loc[idx] == local_obs["TMEAN"]
432
+ local_min = tmin.loc[idx] == local_obs["TMEAN"]
433
+ # extract x and y values
434
+ x_max = local_obs[local_max]["DATE"]
435
+ y_max = local_obs[local_max]["TMEAN"]
436
+ x_min = local_obs[local_min]["DATE"]
437
+ y_min = local_obs[local_min]["TMEAN"]
438
+ xtreme_hi = ax_t.scatter(
439
+ x_max.values, y_max.values, c="#d6604d", marker="x"
440
+ )
441
+ xtreme_lo = ax_t.scatter(
442
+ x_min.values, y_min.values, c="#4393c3", marker="x"
443
+ )
444
+
445
+ xlim = ax_t.get_xlim()
446
+ ax_t.hlines(0, *xlim, linestyles="--")
447
+ # grid
448
+ ax_t.grid()
449
+
450
+ # labels
451
+ ax_t.set_xlim(start_date, end_date)
452
+ if not (plot_tmin == "auto" and plot_tmin == "auto"):
453
+ ax_t.set_ylim(plot_tmin, plot_tmax)
454
+ ax_t.set_ylabel("Temperature in °C")
455
+ ax_t.set_xlabel("Date")
456
+ if title:
457
+ ax_t.set_title(title)
458
+
459
+ # add legend
460
+ legend_handle_t = [fb, cm, cm_hi, fill_r, fill_b]
461
+ legend_text_t = [
462
+ "Observed Temperatures",
463
+ "Climatological Mean",
464
+ "Std of Climatological Mean",
465
+ "Above average Temperature",
466
+ "Below average Temperature",
467
+ ]
468
+ if plot_extrema:
469
+ legend_handle_t.extend([xtreme_hi, xtreme_lo])
470
+ legend_text_t.extend(["Record High on Date", "Record Low on Date"])
471
+
472
+ # PRECIPITATION#
473
+ # legend handles
474
+ legend_handle_p = []
475
+ legend_text_p = []
476
+
477
+ # precipitation
478
+ rain = ax_p.bar(
479
+ x=x_dates_short["DATE"].values,
480
+ height=df_obs["PRCP"].values,
481
+ fc="#4393c3",
482
+ alpha=1,
483
+ )
484
+ legend_handle_p.append(rain)
485
+ legend_text_p.append("Precipitation")
486
+
487
+ # grid
488
+ ax_p.grid()
489
+ # labels
490
+ ax_p.set_ylabel("Precipitation in mm")
491
+ ax_p.set_xlabel("Date")
492
+ # y-axis scaling
493
+ ax_p.set_ylim(bottom=0)
494
+ if isinstance(plot_pmax, (int, float)):
495
+ ax_p.set_ylim(top=plot_pmax)
496
+
497
+ # snow
498
+ # guarded by the show_snow_accumulation reassignment above (skipped when
499
+ # the window has no snowfall, so last_snow_date/snow_acc exist)
500
+ if show_snow_accumulation and ("SNOW" in df_obs.columns):
501
+ ax2_snow = ax_p.twinx()
502
+ # plots
503
+ sn_acc = ax2_snow.fill_between(
504
+ x=x_dates_short.loc[:last_snow_date, "DATE"].values,
505
+ y1=snow_acc.loc[:last_snow_date] / 10,
506
+ facecolor="k",
507
+ alpha=0.2,
508
+ )
509
+ _ = ax2_snow.plot(
510
+ x_dates_short.loc[last_snow_date:, "DATE"].values,
511
+ snow_acc.loc[last_snow_date:] / 10,
512
+ c="k",
513
+ alpha=0.2,
514
+ ls="--",
515
+ )
516
+ # y-axis label
517
+ ax2_snow.set_ylabel("Cumulative Snowfall in cm")
518
+ # legend
519
+ legend_handle_p.append(sn_acc)
520
+ legend_text_p.append("Cumulative Snowfall")
521
+ # y-axis scaling
522
+ ax2_snow.set_ylim(bottom=0)
523
+ if isinstance(plot_snowmax, (int, float)):
524
+ ax2_snow.set_ylim(top=plot_snowmax)
525
+
526
+ # Show nodata - make function
527
+ lo, hi = ax_t.get_ylim()
528
+ nanvals_t = x_dates_short["DATE"].loc[pd.isna(df_obs["TMEAN"])]
529
+ nan_bar_t = ax_t.bar(
530
+ x=nanvals_t,
531
+ height=hi - lo,
532
+ bottom=lo,
533
+ width=1,
534
+ edgecolor=None,
535
+ facecolor="k",
536
+ alpha=0.2,
537
+ )
538
+ if len(nan_bar_t) > 0:
539
+ legend_handle_t.append(nan_bar_t)
540
+ legend_text_t.append("No Data")
541
+
542
+ lo, hi = ax_p.get_ylim()
543
+ nanvals_p = x_dates_short["DATE"].loc[pd.isna(df_obs["PRCP"])]
544
+ nan_bar_p = ax_p.bar(
545
+ x=nanvals_p,
546
+ height=hi - lo,
547
+ bottom=lo,
548
+ width=1,
549
+ edgecolor=None,
550
+ facecolor="k",
551
+ alpha=0.2,
552
+ )
553
+ if len(nan_bar_p) > 0:
554
+ legend_handle_p.append(nan_bar_p)
555
+ legend_text_p.append("No Data")
556
+
557
+ # add Legends
558
+ ax_t.legend(
559
+ legend_handle_t,
560
+ legend_text_t,
561
+ loc="lower center",
562
+ fontsize=legend_fontsize,
563
+ ncol=4,
564
+ bbox_to_anchor=(0.5, 1.02),
565
+ ) # -0.35))
566
+ ax_p.legend(
567
+ legend_handle_p, legend_text_p, loc="upper left", fontsize=legend_fontsize
568
+ )
569
+
570
+ # set locator to monthly
571
+ locator = dates.MonthLocator()
572
+ ax_t.xaxis.set_major_locator(locator)
573
+ 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()
581
+
582
+ # Save Figure
583
+ if save_path:
584
+ fig.savefig(save_path) # , figsize=figsize, dpi=dpi)
585
+ # Show plot if chosen, destroy figure object at the end
586
+ if show_plot:
587
+ plt.show()
588
+ if return_plot:
589
+ return fig
590
+ else:
591
+ plt.close(fig)
592
+
593
+ def plot_monthly_barchart(
594
+ self,
595
+ start_date,
596
+ end_date,
597
+ information="Temperature",
598
+ show_plot=True,
599
+ anomaly=False,
600
+ anomaly_type="absolute",
601
+ trailing_mean=None,
602
+ save_path=False,
603
+ figsize=(9, 4),
604
+ dpi=100,
605
+ legend_fontsize="x-small",
606
+ return_plot=False,
607
+ engine="matplotlib",
608
+ ):
609
+ # legend handles
610
+ legend_handle = []
611
+ legend_text = []
612
+
613
+ # setup plot arguments
614
+ plot_kwargs = setup_monthly_plot_props(information, anomaly)
615
+
616
+ # Data Preprocessing
617
+ if parse_dates(end_date) > self.dataset.data["DATE"].max():
618
+ end_date = self.dataset.data["DATE"].max()
619
+ data_monthly = DS_monthly(
620
+ self.dataset, start=self.dataset.data["DATE"].min(), end=end_date
621
+ )
622
+ data_monthly.calculate_monthly_statistics()
623
+ data_clim = DS_monthly(
624
+ self.dataset, start=self.climate_start, end=self.climate_end
625
+ )
626
+ data_clim.calculate_monthly_climate()
627
+
628
+ data = data_monthly.monthly_aggregate.reset_index(drop=False)
629
+ df_clim = data_clim.monthly_climate.reset_index(drop=False)
630
+
631
+ if (
632
+ plot_kwargs["value_column"] == "prcp_diff"
633
+ and df_clim["prcp_sum"].isna().any()
634
+ ):
635
+ print("Invalid precipitation values, information not available!")
636
+ return None
637
+
638
+ data["DATE"] = data.apply(lambda x: parse_dates_YM(x["DATE_YM"]), axis=1)
639
+ data["Month"] = data.apply(lambda x: parse_dates_YM(x["DATE_YM"]).month, axis=1)
640
+ data["Year"] = data.apply(lambda x: parse_dates_YM(x["DATE_YM"]).year, axis=1)
641
+ data = (
642
+ data.set_index("Month", drop=False)
643
+ .join(df_clim.set_index("Month", drop=False), rsuffix="_clim")
644
+ .sort_values("DATE_YM")
645
+ )
646
+ data["tmean_diff"] = data["tmean_doy_mean"] - data["tmean_doy_mean_clim"]
647
+ data["prcp_diff"] = data["prcp_sum"] - data["prcp_sum_clim"]
648
+ data = data.set_index("DATE", drop=False)
649
+
650
+ # trailing mean calculation
651
+ if trailing_mean:
652
+ data = calc_trailing_mean(
653
+ data, trailing_mean, plot_kwargs["value_column"], "trailing_values"
654
+ )
655
+
656
+ # ----- plotly engine: interactive figure -----
657
+ if engine == "plotly":
658
+ from noaaplotter.figures import make_monthly_figure
659
+
660
+ fig_pl = make_monthly_figure(
661
+ data, plot_kwargs, trailing_mean=trailing_mean,
662
+ figsize=(int(figsize[0] * 100), int(figsize[1] * 100)),
663
+ )
664
+ if save_path:
665
+ fig_pl.write_html(save_path if str(save_path).endswith(".html")
666
+ else str(save_path) + ".html")
667
+ return fig_pl
668
+
669
+ # PLOT part
670
+ fig = plt.figure(figsize=figsize, dpi=dpi)
671
+ ax = fig.add_subplot(111)
672
+ data_low = data[data[plot_kwargs["value_column"]] < 0]
673
+ data_high = data[data[plot_kwargs["value_column"]] >= 0]
674
+ bar_low = ax.bar(
675
+ x=data_low["DATE"],
676
+ height=data_low[plot_kwargs["value_column"]],
677
+ width=30,
678
+ align="edge",
679
+ color=plot_kwargs["fc_low"],
680
+ edgecolor="white",
681
+ linewidth=0.5,
682
+ )
683
+ # Fix for absolute values
684
+ if len(bar_low) > 1:
685
+ legend_handle.append(bar_low)
686
+ legend_text.append(plot_kwargs["legend_label_below"])
687
+ bar_high = ax.bar(
688
+ x=data_high["DATE"],
689
+ height=data_high[plot_kwargs["value_column"]],
690
+ width=30,
691
+ align="edge",
692
+ color=plot_kwargs["fc_high"],
693
+ edgecolor="white",
694
+ linewidth=0.5,
695
+ )
696
+ legend_handle.append(bar_high)
697
+ legend_text.append(plot_kwargs["legend_label_above"])
698
+ if trailing_mean:
699
+ line_tr_mean = ax.plot(data["DATE"], data["trailing_values"], c="k")
700
+ legend_handle.append(line_tr_mean[0])
701
+ legend_text.append("Trailing mean: {} months".format(trailing_mean))
702
+ ax.xaxis.set_major_locator(dates.YearLocator())
703
+ ax.tick_params(axis="x", rotation=90)
704
+ ax.grid(True)
705
+
706
+ # x-limit
707
+ ax.set_xlim(start_date, end_date)
708
+
709
+ # labels
710
+ ax.set_ylabel(plot_kwargs["y_label"])
711
+ ax.set_xlabel("Date")
712
+ ax.set_title(plot_kwargs["title"])
713
+ # add legend
714
+ ax.legend(legend_handle, legend_text, loc="best", fontsize=legend_fontsize)
715
+
716
+ fig.tight_layout()
717
+ # Save Figure
718
+ if save_path:
719
+ fig.savefig(save_path) # , figsize=figsize, dpi=dpi)
720
+ # Show plot if chosen, destroy figure object at the end
721
+ if show_plot:
722
+ plt.show()
723
+ if return_plot:
724
+ return fig
725
+ else:
726
+ plt.close(fig)