Coverage for src/CSET/operators/plot.py: 82%
1122 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-28 09:59 +0000
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-28 09:59 +0000
1# © Crown copyright, Met Office (2022-2025) and CSET contributors.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
15"""Operators to produce various kinds of plots."""
17import fcntl
18import importlib.resources
19import itertools
20import json
21import logging
22import math
23import os
24import sys
25from typing import Literal
27import cartopy.crs as ccrs
28import cartopy.feature as cfeature
29import iris
30import iris.coords
31import iris.cube
32import iris.exceptions
33import iris.plot as iplt
34import matplotlib as mpl
35import matplotlib.pyplot as plt
36import numpy as np
37from cartopy.mpl.geoaxes import GeoAxes
38from iris.cube import Cube
39from markdown_it import MarkdownIt
40from mpl_toolkits.axes_grid1.inset_locator import inset_axes
42from CSET._common import (
43 filename_slugify,
44 get_recipe_metadata,
45 iter_maybe,
46 render_file,
47 slugify,
48)
49from CSET.operators._colormaps import (
50 colorbar_map_levels,
51 get_model_colors_map,
52)
53from CSET.operators._utils import (
54 calc_array_stats,
55 check_sequence_coordinate,
56 check_single_cube,
57 check_stamp_coordinate,
58 fully_equalise_attributes,
59 get_cube_yxcoordname,
60 get_num_models,
61 is_transect,
62 slice_over_maybe,
63 validate_cube_shape,
64 validate_cubes_coords,
65)
66from CSET.operators.collapse import collapse
67from CSET.operators.misc import _extract_common_time_points
68from CSET.operators.regrid import regrid_onto_cube
70logger = logging.getLogger(__name__)
72# Use a non-interactive plotting backend.
73mpl.use("agg")
76############################
77# Private helper functions #
78############################
81def in_sphinx_gallery():
82 """Test if running plot code in sphinx-gallery context."""
83 return "sphinx_gallery" in sys.modules
86def _append_to_plot_index(plot_index: list) -> list:
87 """Add plots into the plot index, returning the complete plot index."""
88 with open("meta.json", "r+t", encoding="UTF-8") as fp:
89 fcntl.flock(fp, fcntl.LOCK_EX)
90 fp.seek(0)
91 meta = json.load(fp)
92 complete_plot_index = meta.get("plots", [])
93 complete_plot_index = complete_plot_index + plot_index
94 meta["plots"] = complete_plot_index
95 if os.getenv("CYLC_TASK_CYCLE_POINT") and not bool(
96 os.getenv("DO_CASE_AGGREGATION")
97 ):
98 meta["case_date"] = os.getenv("CYLC_TASK_CYCLE_POINT", "")
99 fp.seek(0)
100 fp.truncate()
101 json.dump(meta, fp, indent=2)
102 return complete_plot_index
105def _make_plot_html_page(plots: list):
106 """Create a HTML page to display a plot image."""
107 # Debug check that plots actually contains some strings.
108 assert isinstance(plots[0], str)
110 # Load HTML template file.
111 operator_files = importlib.resources.files()
112 template_file = operator_files.joinpath("_plot_page_template.html")
114 # Get some metadata.
115 meta = get_recipe_metadata()
116 title = meta.get("title", "Untitled")
117 description = MarkdownIt().render(meta.get("description", "*No description.*"))
119 # Prepare template variables.
120 variables = {
121 "title": title,
122 "description": description,
123 "initial_plot": plots[0],
124 "plots": plots,
125 "title_slug": slugify(title),
126 }
128 # Render template.
129 html = render_file(template_file, **variables)
131 # Save completed HTML.
132 with open("index.html", "wt", encoding="UTF-8") as fp:
133 fp.write(html)
136def _save_close_figure(figure, plot_type: str, filename: str):
137 """Save generated plot figure file and close figure.
139 If running documentation gallery generation, avoid saving to file.
141 Parameters
142 ----------
143 figure:
144 Matplotlib Figure object holding all plot elements.
145 plot_type: str
146 String identifier for plot type for logging information.
147 filename: str
148 Filename for saved figure.
149 """
150 if not in_sphinx_gallery():
151 figure.savefig(filename, bbox_inches="tight", dpi=_get_plot_resolution())
152 logger.info("Saved %s plot to %s", plot_type, filename)
153 plt.close(figure)
156def _setup_spatial_map(
157 cube: iris.cube.Cube,
158 figure,
159 cmap,
160 grid_size: tuple[int, int] | None = None,
161 subplot: int | None = None,
162):
163 """Define map projections, extent and add coastlines and borderlines for spatial plots.
165 For spatial map plots, a relevant map projection for rotated or non-rotated inputs
166 is specified, and map extent defined based on the input data.
168 Parameters
169 ----------
170 cube: Cube
171 2 dimensional (lat and lon) Cube of the data to plot.
172 figure:
173 Matplotlib Figure object holding all plot elements.
174 cmap:
175 Matplotlib colormap.
176 grid_size: (int, int), optional
177 Size of grid (rows, cols) for subplots if multiple spatial subplots in figure.
178 subplot: int, optional
179 Subplot index if multiple spatial subplots in figure.
181 Returns
182 -------
183 axes:
184 Matplotlib GeoAxes definition.
185 """
186 # Identify min/max plot bounds.
187 try:
188 lat_axis, lon_axis = get_cube_yxcoordname(cube)
189 xmin = np.nanmin(cube.coord(lon_axis).points)
190 xmax = np.nanmax(cube.coord(lon_axis).points)
191 ymin = np.nanmin(cube.coord(lat_axis).points)
192 ymax = np.nanmax(cube.coord(lat_axis).points)
194 # Adjust bounds within +/- 180.0 if x dimension extends beyond half-globe.
195 if np.abs(xmax - xmin) > 180.0:
196 xmin = xmin - 180.0
197 xmax = xmax - 180.0
198 logger.debug("Adjusting plot bounds to fit global extent.")
200 # Consider map projection orientation.
201 # Adapting orientation enables plotting across international dateline.
202 # Users can adapt the default central_longitude if alternative projections views.
203 if xmax > 180.0 or xmin < -180.0:
204 central_longitude = 180.0
205 else:
206 central_longitude = 0.0
208 # Define spatial map projection.
209 coord_system = cube.coord(lat_axis).coord_system
210 if isinstance(coord_system, iris.coord_systems.RotatedGeogCS):
211 # Define rotated pole map projection for rotated pole inputs.
212 projection = ccrs.RotatedPole(
213 pole_longitude=coord_system.grid_north_pole_longitude,
214 pole_latitude=coord_system.grid_north_pole_latitude,
215 central_rotated_longitude=central_longitude,
216 )
217 crs = projection
218 elif isinstance(coord_system, iris.coord_systems.TransverseMercator): 218 ↛ 220line 218 didn't jump to line 220 because the condition on line 218 was never true
219 # Define Transverse Mercator projection for TM inputs.
220 projection = ccrs.TransverseMercator(
221 central_longitude=coord_system.longitude_of_central_meridian,
222 central_latitude=coord_system.latitude_of_projection_origin,
223 false_easting=coord_system.false_easting,
224 false_northing=coord_system.false_northing,
225 scale_factor=coord_system.scale_factor_at_central_meridian,
226 )
227 crs = projection
228 else:
229 # Assume polar projection for regional grids encompassing N. Pole
230 if ymin > 20.0 and ymax > 80.0:
231 projection = ccrs.NorthPolarStereo(central_longitude=0.0)
232 elif ymin < -80.0 and ymax < -20.0:
233 projection = ccrs.SouthPolarStereo(central_longitude=central_longitude)
234 # Define regular map projection for non-rotated pole inputs.
235 # Alternatives might include e.g. for global model outputs:
236 # projection=ccrs.Robinson(central_longitude=X.y, globe=None)
237 # projection = ccrs.NearsidePerspective(
238 # central_longitude=180.0,
239 # central_latitude=0,
240 # satellite_height=35785831,
241 # )
242 # See also https://scitools.org.uk/cartopy/docs/v0.15/crs/projections.html.
243 else:
244 projection = ccrs.PlateCarree(central_longitude=central_longitude)
245 crs = ccrs.PlateCarree()
247 # Define axes for plot (or subplot) with required map projection.
248 if subplot is not None:
249 axes = figure.add_subplot(
250 grid_size[0], grid_size[1], subplot, projection=projection
251 )
252 else:
253 axes = figure.add_subplot(projection=projection)
255 # Add coastlines and borderlines if cube contains x and y map coordinates.
256 # Avoid adding lines for specific fixed ancillary spatial plots
257 if any(name in cube.name() for name in ("land_", "orography", "altitude")):
258 pass
259 else:
260 if cmap.name in ["viridis", "Greys"]:
261 coastcol = "magenta"
262 else:
263 coastcol = "black"
264 logger.debug("Plotting coastlines and borderlines in colour %s.", coastcol)
265 axes.coastlines(resolution="10m", color=coastcol, alpha=0.8)
266 axes.add_feature(cfeature.BORDERS, edgecolor=coastcol, alpha=0.3)
268 # Add gridlines.
269 gl = axes.gridlines(
270 alpha=0.3,
271 draw_labels=True,
272 dms=False,
273 x_inline=False,
274 y_inline=False,
275 )
276 gl.top_labels = False
277 gl.right_labels = False
278 if subplot:
279 gl.bottom_labels = False
280 gl.left_labels = False
281 if subplot % grid_size[1] == 1:
282 gl.left_labels = True
283 if subplot > ((grid_size[0] - 1) * grid_size[1]): 283 ↛ 288line 283 didn't jump to line 288 because the condition on line 283 was always true
284 gl.bottom_labels = True
286 # If is lat/lon spatial map, fix extent to keep plot tight.
287 # Specifying crs within set_extent helps ensure only data region is shown.
288 if isinstance(
289 coord_system, (iris.coord_systems.GeogCS, iris.coord_systems.RotatedGeogCS)
290 ):
291 axes.set_extent([xmin, xmax, ymin, ymax], crs=crs)
293 except ValueError:
294 # Skip if not both x and y map coordinates.
295 axes = figure.gca()
297 return axes
300def _get_plot_resolution() -> int:
301 """Get resolution of rasterised plots in pixels per inch."""
302 return get_recipe_metadata().get("plot_resolution", 100)
305def _get_start_end_strings(seq_coord: iris.coords.Coord, use_bounds: bool):
306 """Return title and filename based on start and end points or bounds."""
307 if use_bounds and seq_coord.has_bounds():
308 vals = seq_coord.bounds.flatten()
309 else:
310 vals = seq_coord.points
311 start = seq_coord.units.title(vals[0])
312 end = seq_coord.units.title(vals[-1])
314 if start == end:
315 sequence_title = f"\n [{start}]"
316 sequence_fname = f"_{filename_slugify(start)}"
317 else:
318 sequence_title = f"\n [{start} to {end}]"
319 sequence_fname = f"_{filename_slugify(start)}_{filename_slugify(end)}"
321 # Do not include time if coord set to zero.
322 if (
323 seq_coord.units == "hours since 0001-01-01 00:00:00"
324 and vals[0] == 0
325 and vals[-1] == 0
326 ):
327 sequence_title = ""
328 sequence_fname = ""
330 return sequence_title, sequence_fname
333def _set_title_and_filename(
334 seq_coord: iris.coords.Coord,
335 nplot: int,
336 recipe_title: str,
337 filename: str,
338 model_name: str | None = None,
339):
340 """Set plot title and filename based on cube coordinate.
342 Parameters
343 ----------
344 sequence_coordinate: iris.coords.Coord
345 Coordinate about which to make a plot sequence.
346 nplot: int
347 Number of output plots to generate - controls title/naming.
348 recipe_title: str
349 Default plot title, potentially to update.
350 filename: str
351 Input plot filename, potentially to update.
353 Returns
354 -------
355 plot_title: str
356 Output formatted plot title string, based on plotted data.
357 plot_filename: str
358 Output formatted plot filename string.
359 """
360 ndim = seq_coord.ndim
361 npoints = np.size(seq_coord.points)
362 sequence_title = ""
363 sequence_fname = ""
365 # Case 1: Multiple dimension sequence input - list number of aggregated cases
366 # (e.g. aggregation histogram plots)
367 if ndim > 1:
368 ncase = np.shape(seq_coord)[0]
369 sequence_title = f"\n [{ncase} cases]"
370 sequence_fname = f"_{ncase}cases"
372 # Case 2: Single dimension input
373 else:
374 # Single sequence point
375 if npoints == 1:
376 if nplot > 1:
377 # Default labels for sequence inputs
378 sequence_value = seq_coord.units.title(seq_coord.points[0])
379 sequence_value = sequence_value.replace(" unknown", "")
380 sequence_title = f"\n [{sequence_value}]"
381 sequence_fname = f"_{filename_slugify(sequence_value)}"
382 else:
383 # Aggregated attribute available where input collapsed over aggregation
384 try:
385 ncase = seq_coord.attributes["number_reference_times"]
386 sequence_title = f"\n [{ncase} cases]"
387 sequence_fname = f"_{ncase}cases"
388 except KeyError:
389 sequence_title, sequence_fname = _get_start_end_strings(
390 seq_coord, use_bounds=seq_coord.has_bounds()
391 )
392 # Multiple sequence (e.g. time) points
393 else:
394 sequence_title, sequence_fname = _get_start_end_strings(
395 seq_coord, use_bounds=False
396 )
398 # Set plot title and filename
399 plot_title = f"{recipe_title}{sequence_title}"
401 # Set plot filename, defaulting to user input if provided.
402 if filename is None:
403 filename = slugify(recipe_title)
404 plot_filename = f"{filename.rsplit('.', 1)[0]}{sequence_fname}.png"
405 else:
406 if nplot > 1:
407 plot_filename = f"{filename.rsplit('.', 1)[0]}{sequence_fname}.png"
408 else:
409 plot_filename = f"{filename.rsplit('.', 1)[0]}.png"
411 if model_name: 411 ↛ 412line 411 didn't jump to line 412 because the condition on line 411 was never true
412 plot_filename = f"{model_name}_{plot_filename}"
413 plot_title = f"{model_name}_{plot_title}"
415 return plot_title, plot_filename
418def _select_series_coord(cube, series_coordinate):
419 """Determine the grid coordinates to use to calculate grid spacing."""
420 spacing_coordinates = ("frequency", "physical_wavenumber", "wavelength")
421 if series_coordinate in spacing_coordinates: 421 ↛ 427line 421 didn't jump to line 427 because the condition on line 421 was always true
422 # Try the requested coordinate first then the fallbacks in order.
423 fallbacks = [series_coordinate] + [
424 c for c in spacing_coordinates if c != series_coordinate
425 ]
426 else:
427 fallbacks = {series_coordinate}
429 # Try each possible coordinate.
430 for coord in fallbacks:
431 try:
432 return cube.coord(coord)
433 except iris.exceptions.CoordinateNotFoundError:
434 logger.debug("Coordinate %s not found.", coord)
436 # If we get here, none of the fallback options were found.
437 raise iris.exceptions.CoordinateNotFoundError(
438 f"No valid coordinate found for '{series_coordinate}' "
439 f"or fallback options {fallbacks}"
440 )
443def _set_postage_stamp_title(stamp_coord: iris.coords.Coord) -> str:
444 """Control postage stamp plot output titles based on stamp coordinate."""
445 if stamp_coord.name() == "realization":
446 mtitle = "Member"
447 else:
448 mtitle = stamp_coord.name().capitalize()
450 if stamp_coord.name() == "time":
451 mtitle = f"{stamp_coord.units.title(stamp_coord.points[0])}"
452 else:
453 mtitle = f"{mtitle} #{stamp_coord.points[0]}"
455 return mtitle
458def _set_axis_range(cubes):
459 """Get minimum and maximum from levels information."""
460 levels = None
461 for cube in cubes: 461 ↛ 477line 461 didn't jump to line 477 because the loop on line 461 didn't complete
462 # First check if user-specified "auto" range variable.
463 # This maintains the value of levels as None, so proceed.
464 _, levels, _ = colorbar_map_levels(cube, axis="y")
465 if levels is None:
466 break
467 # If levels is changed, recheck to use the vmin,vmax or
468 # levels-based ranges for histogram plots.
469 _, levels, _ = colorbar_map_levels(cube)
470 logger.debug("levels: %s", levels)
471 if levels is not None: 471 ↛ 461line 471 didn't jump to line 461 because the condition on line 471 was always true
472 vmin = min(levels)
473 vmax = max(levels)
474 logger.debug("Updated vmin, vmax: %s, %s", vmin, vmax)
475 break
477 if levels is None:
478 vmin = min(cb.data.min() for cb in cubes)
479 vmax = max(cb.data.max() for cb in cubes)
481 return vmin, vmax
484def _find_matched_slices(cubes, sequence_coordinate):
485 """Identify matched cubes in CubeList by sequence_coordinate values.
487 Ensures common points are compared for multiple cube inputs.
488 """
489 all_points = sorted(
490 set(
491 itertools.chain.from_iterable(
492 cb.coord(sequence_coordinate).points for cb in cubes
493 )
494 )
495 )
496 all_slices = list(
497 itertools.chain.from_iterable(
498 cb.slices_over(sequence_coordinate) for cb in cubes
499 )
500 )
501 # Matched slices (matched by seq coord point; it may happen that
502 # evaluated models do not cover the same seq coord range, hence matching
503 # necessary)
504 cube_iterables = [
505 iris.cube.CubeList(
506 s for s in all_slices if s.coord(sequence_coordinate).points[0] == point
507 )
508 for point in all_points
509 ]
511 return cube_iterables
514def _plot_and_save_spatial_plot(
515 cube: iris.cube.Cube,
516 filename: str,
517 title: str,
518 method: Literal["contourf", "pcolormesh", "scatter"],
519 overlay_cube: iris.cube.Cube | None = None,
520 contour_cube: iris.cube.Cube | None = None,
521 point_cube: iris.cube.Cube | None = None,
522 **kwargs,
523):
524 """Plot and save a spatial plot.
526 Parameters
527 ----------
528 cube: Cube
529 2 dimensional (lat and lon) Cube of the data to plot.
530 filename: str
531 Filename of the plot to write.
532 title: str
533 Plot title.
534 method: "contourf" | "pcolormesh" | "scatter"
535 The plotting method to use
536 Select choice of "contourf" or "pcolormesh" for gridded data. Use "scatter" for point-based data.
537 overlay_cube: Cube, optional
538 Optional 2 dimensional (lat and lon) Cube of data to overplot on top of base cube
539 contour_cube: Cube, optional
540 Optional 2 dimensional (lat and lon) Cube of data to overplot as contours over base cube
541 point_cube: Cube, optional
542 Optional 1 dimensional (e.g. list of points) or 2 dimensional (lat and lon) Cube of data to overplot as map of scatter points over base cube
543 """
544 # Setup plot details, size, resolution, etc.
545 fig = plt.figure(figsize=(10, 10), facecolor="w", edgecolor="k")
547 # Specify the color bar
548 cmap, levels, norm = colorbar_map_levels(cube)
550 # If overplotting, set required colorbars
551 if overlay_cube:
552 over_cmap, over_levels, over_norm = colorbar_map_levels(overlay_cube)
553 if contour_cube:
554 cntr_cmap, cntr_levels, cntr_norm = colorbar_map_levels(contour_cube)
556 # Setup plot map projection, extent and coastlines and borderlines.
557 axes = _setup_spatial_map(cube, fig, cmap)
559 # Set colorscale bounds
560 try:
561 vmin = min(levels)
562 vmax = max(levels)
563 except TypeError:
564 vmin, vmax = None, None
565 # Ensure to use norm and not vmin/vmax if levels are defined.
566 if norm is not None:
567 vmin = None
568 vmax = None
569 logger.debug("Plotting using defined levels.")
571 # Plot the field.
572 if method == "contourf":
573 plot = iplt.contourf(cube, cmap=cmap, levels=levels, norm=norm)
574 elif method == "pcolormesh":
575 plot = iplt.pcolormesh(cube, cmap=cmap, norm=norm, vmin=vmin, vmax=vmax)
576 elif method == "scatter":
577 # Scatter plot of the field. The marker size is chosen to give
578 # symbols that decrease in size as the number of data points
579 # increases, although the fraction of the figure covered by
580 # symbols increases roughly as N^(1/2), disregarding overlaps,
581 # and has been selected for the default figure size of (10, 10).
582 # Should this be changed, the marker size should be adjusted in
583 # proportion to the area of the figure.
584 mrk_size = int(np.sqrt(2500000.0 / len(cube.data)))
585 lat_axis, lon_axis = get_cube_yxcoordname(cube)
586 plot = iplt.scatter(
587 cube.coord(lon_axis),
588 cube.coord(lat_axis),
589 c=cube.data[:],
590 s=mrk_size,
591 cmap=cmap,
592 edgecolors="k",
593 norm=norm,
594 vmin=vmin,
595 vmax=vmax,
596 )
597 else:
598 raise ValueError(f"Unknown plotting method: {method}")
600 # Overplot overlay field, if required
601 if overlay_cube:
602 try:
603 over_vmin = min(over_levels)
604 over_vmax = max(over_levels)
605 except TypeError:
606 over_vmin, over_vmax = None, None
607 if over_norm is not None: 607 ↛ 608line 607 didn't jump to line 608 because the condition on line 607 was never true
608 over_vmin = None
609 over_vmax = None
610 overlay = iplt.pcolormesh(
611 overlay_cube,
612 cmap=over_cmap,
613 norm=over_norm,
614 alpha=0.8,
615 vmin=over_vmin,
616 vmax=over_vmax,
617 )
618 # Overplot contour field, if required, with contour labelling.
619 if contour_cube:
620 contour = iplt.contour(
621 contour_cube,
622 colors="darkgray",
623 levels=cntr_levels,
624 norm=cntr_norm,
625 alpha=0.5,
626 linestyles="--",
627 linewidths=1,
628 )
629 plt.clabel(contour)
630 # Overplot valid elements of point-based field, if required.
631 # Check for non-masked points only to avoid plotting missing data.
632 if point_cube:
633 mrk_size = int(np.sqrt(2500000.0 / len(point_cube.data)))
634 lat_axis, lon_axis = get_cube_yxcoordname(point_cube)
635 lon_coord = point_cube.coord(lon_axis)
636 lat_coord = point_cube.coord(lat_axis)
637 valid = ~point_cube.data.mask
638 valid_lon = iris.coords.AuxCoord(
639 lon_coord.points[valid],
640 standard_name=lon_coord.standard_name,
641 units=lon_coord.units,
642 coord_system=lon_coord.coord_system,
643 )
644 valid_lat = iris.coords.AuxCoord(
645 lat_coord.points[valid],
646 standard_name=lat_coord.standard_name,
647 units=lat_coord.units,
648 coord_system=lat_coord.coord_system,
649 )
650 iplt.scatter(
651 valid_lon,
652 valid_lat,
653 c=point_cube.data[valid],
654 s=mrk_size,
655 cmap=cmap,
656 edgecolors="k",
657 norm=norm,
658 vmin=vmin,
659 vmax=vmax,
660 )
662 # Check to see if transect, and if so, adjust y axis.
663 if is_transect(cube):
664 if "pressure" in [coord.name() for coord in cube.coords()]:
665 axes.invert_yaxis()
666 axes.set_yscale("log")
667 axes.set_ylim(1100, 100)
668 # If both model_level_number and level_height exists, iplt can construct
669 # plot as a function of height above orography (NOT sea level).
670 elif {"model_level_number", "level_height"}.issubset( 670 ↛ 675line 670 didn't jump to line 675 because the condition on line 670 was always true
671 {coord.name() for coord in cube.coords()}
672 ):
673 axes.set_yscale("log")
675 axes.set_title(
676 f"{title}\n"
677 f"Start Lat: {cube.attributes['transect_coords'].split('_')[0]}"
678 f" Start Lon: {cube.attributes['transect_coords'].split('_')[1]}"
679 f" End Lat: {cube.attributes['transect_coords'].split('_')[2]}"
680 f" End Lon: {cube.attributes['transect_coords'].split('_')[3]}",
681 fontsize=16,
682 )
684 # Inset code
685 axins = inset_axes(
686 axes,
687 width="20%",
688 height="20%",
689 loc="upper right",
690 axes_class=GeoAxes,
691 axes_kwargs={"map_projection": ccrs.PlateCarree()},
692 )
694 # Slightly transparent to reduce plot blocking.
695 axins.patch.set_alpha(0.4)
697 axins.coastlines(resolution="50m")
698 axins.add_feature(cfeature.BORDERS, linewidth=0.3)
700 SLat, SLon, ELat, ELon = (
701 float(coord) for coord in cube.attributes["transect_coords"].split("_")
702 )
704 # Draw line between them
705 axins.plot(
706 [SLon, ELon], [SLat, ELat], color="black", transform=ccrs.PlateCarree()
707 )
709 # Plot points (note: lon, lat order for Cartopy)
710 axins.plot(SLon, SLat, marker="x", color="green", transform=ccrs.PlateCarree())
711 axins.plot(ELon, ELat, marker="x", color="red", transform=ccrs.PlateCarree())
713 lon_min, lon_max = sorted([SLon, ELon])
714 lat_min, lat_max = sorted([SLat, ELat])
716 # Midpoints
717 lon_mid = (lon_min + lon_max) / 2
718 lat_mid = (lat_min + lat_max) / 2
720 # Maximum half-range
721 half_range = max(lon_max - lon_min, lat_max - lat_min) / 2
722 if half_range == 0: # points identical → provide small default 722 ↛ 726line 722 didn't jump to line 726 because the condition on line 722 was always true
723 half_range = 1
725 # Set square extent
726 axins.set_extent(
727 [
728 lon_mid - half_range,
729 lon_mid + half_range,
730 lat_mid - half_range,
731 lat_mid + half_range,
732 ],
733 crs=ccrs.PlateCarree(),
734 )
736 # Ensure square aspect
737 axins.set_aspect("equal")
739 else:
740 # Add title.
741 axes.set_title(title, fontsize=16)
743 # Adjust padding if spatial plot or transect
744 if is_transect(cube):
745 yinfopad = -0.1
746 ycbarpad = 0.1
747 else:
748 yinfopad = 0.01
749 ycbarpad = 0.042
751 # Add watermark with min/max/mean. Currently not user togglable.
752 # In the bbox dictionary, fc and ec are hex colour codes for grey shade.
753 cube_min, cube_max, cube_mean = calc_array_stats(cube.data)
754 axes.annotate(
755 f"Min: {cube_min:.3g} Max: {cube_max:.3g} Mean: {cube_mean:.3g}",
756 xy=(0.025, yinfopad),
757 xycoords="axes fraction",
758 xytext=(-5, 5),
759 textcoords="offset points",
760 ha="left",
761 va="bottom",
762 size=11,
763 bbox={"boxstyle": "round", "fc": "#cccccc", "ec": "#808080", "alpha": 0.9},
764 )
766 # Add secondary colour bar for overlay_cube field if required.
767 if overlay_cube:
768 cbarB = fig.colorbar(
769 overlay, orientation="horizontal", location="bottom", pad=0.0, shrink=0.7
770 )
771 cbarB.set_label(label=f"{overlay_cube.name()} ({overlay_cube.units})", size=14)
772 # add ticks and tick_labels for every levels if less than 20 levels exist
773 if over_levels is not None and len(over_levels) < 20: 773 ↛ 774line 773 didn't jump to line 774 because the condition on line 773 was never true
774 cbarB.set_ticks(over_levels)
775 cbarB.set_ticklabels([f"{level:.2f}" for level in over_levels])
776 if any(
777 var in overlay_cube.name()
778 for var in ("rainfall", "snowfall", "visibility")
779 ):
780 cbarB.set_ticklabels([f"{level:.3g}" for level in over_levels])
781 logger.debug("Set secondary colorbar ticks and labels.")
783 # Add main colour bar.
784 cbar = fig.colorbar(
785 plot, orientation="horizontal", location="bottom", pad=ycbarpad, shrink=0.7
786 )
788 cbar.set_label(label=f"{cube.name()} ({cube.units})", size=14)
789 # add ticks and tick_labels for every levels if less than 20 levels exist
790 if levels is not None and len(levels) < 20:
791 cbar.set_ticks(levels)
792 cbar.set_ticklabels([f"{level:.2f}" for level in levels])
793 if any(var in cube.name() for var in ("rainfall", "snowfall", "visibility")): 793 ↛ 796line 793 didn't jump to line 796 because the condition on line 793 was always true
794 cbar.set_ticklabels([f"{level:.3g}" for level in levels])
795 # Tick labels for rainfall rates from Nimrod radar data.
796 if "rainfall rate composite" in cube.name(): 796 ↛ 797line 796 didn't jump to line 797 because the condition on line 796 was never true
797 cbar.set_ticklabels([f"{level:.3g}" for level in levels])
798 # Tick labels for rain accumulations from Nimrod radar data.
799 if "rain accumulation" in cube.name(): 799 ↛ 800line 799 didn't jump to line 800 because the condition on line 799 was never true
800 cbar.set_ticklabels([f"{level:.3g}" for level in levels])
801 if "wts accumulation" in cube.name(): 801 ↛ 802line 801 didn't jump to line 802 because the condition on line 801 was never true
802 tick_levels = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
803 cbar.minorticks_off()
804 cbar.set_ticks(tick_levels)
805 cbar.set_ticklabels([f"{level:.3g}" for level in tick_levels])
806 cbar.set_label(label=f"{cube.name()}", size=14)
807 # Tick labels for model rainfall data.
808 if "surface_microphysical" in cube.name(): 808 ↛ 811line 808 didn't jump to line 811 because the condition on line 808 was always true
809 cbar.set_ticklabels([f"{level:.3g}" for level in levels])
810 # Tick labels for Nimrod weights data.
811 logger.debug("Set colorbar ticks and labels.")
813 # Save plot.
814 _save_close_figure(fig, "spatial", filename)
817def _plot_and_save_postage_stamp_spatial_plot(
818 cube: iris.cube.Cube,
819 filename: str,
820 stamp_coordinate: str,
821 title: str,
822 method: Literal["contourf", "pcolormesh"],
823 overlay_cube: iris.cube.Cube | None = None,
824 contour_cube: iris.cube.Cube | None = None,
825 **kwargs,
826):
827 """Plot postage stamp spatial plots from an ensemble.
829 Parameters
830 ----------
831 cube: Cube
832 Iris cube of data to be plotted. It must have the stamp coordinate.
833 filename: str
834 Filename of the plot to write.
835 stamp_coordinate: str
836 Coordinate that becomes different plots.
837 method: "contourf" | "pcolormesh"
838 The plotting method to use.
839 overlay_cube: Cube, optional
840 Optional 2 dimensional (lat and lon) Cube of data to overplot on top of base cube
841 contour_cube: Cube, optional
842 Optional 2 dimensional (lat and lon) Cube of data to overplot as contours over base cube
844 Raises
845 ------
846 ValueError
847 If the cube doesn't have the right dimensions.
848 """
849 # Use the smallest square grid that will fit the members.
850 nmember = len(cube.coord(stamp_coordinate).points)
851 grid_rows = int(math.sqrt(nmember))
852 grid_size = math.ceil(nmember / grid_rows)
854 fig = plt.figure(
855 figsize=(10, 10 * max(grid_rows / grid_size, 0.5)), facecolor="w", edgecolor="k"
856 )
858 # Specify the color bar
859 cmap, levels, norm = colorbar_map_levels(cube)
860 # If overplotting, set required colorbars
861 if overlay_cube: 861 ↛ 862line 861 didn't jump to line 862 because the condition on line 861 was never true
862 over_cmap, over_levels, over_norm = colorbar_map_levels(overlay_cube)
863 if contour_cube: 863 ↛ 864line 863 didn't jump to line 864 because the condition on line 863 was never true
864 cntr_cmap, cntr_levels, cntr_norm = colorbar_map_levels(contour_cube)
866 # Make a subplot for each member.
867 for member, subplot in zip(
868 cube.slices_over(stamp_coordinate),
869 range(1, grid_size * grid_rows + 1),
870 strict=False,
871 ):
872 # Setup subplot map projection, extent and coastlines and borderlines.
873 axes = _setup_spatial_map(
874 member, fig, cmap, grid_size=(grid_rows, grid_size), subplot=subplot
875 )
876 if method == "contourf":
877 # Filled contour plot of the field.
878 plot = iplt.contourf(member, cmap=cmap, levels=levels, norm=norm)
879 elif method == "pcolormesh":
880 if levels is not None:
881 vmin = min(levels)
882 vmax = max(levels)
883 else:
884 raise TypeError("Unknown vmin and vmax range.")
885 vmin, vmax = None, None
886 # pcolormesh plot of the field and ensure to use norm and not vmin/vmax
887 # if levels are defined.
888 if norm is not None: 888 ↛ 889line 888 didn't jump to line 889 because the condition on line 888 was never true
889 vmin = None
890 vmax = None
891 # pcolormesh plot of the field.
892 plot = iplt.pcolormesh(member, cmap=cmap, norm=norm, vmin=vmin, vmax=vmax)
893 else:
894 raise ValueError(f"Unknown plotting method: {method}")
896 # Overplot overlay field, if required
897 if overlay_cube: 897 ↛ 898line 897 didn't jump to line 898 because the condition on line 897 was never true
898 try:
899 over_vmin = min(over_levels)
900 over_vmax = max(over_levels)
901 except TypeError:
902 over_vmin, over_vmax = None, None
903 if over_norm is not None:
904 over_vmin = None
905 over_vmax = None
906 iplt.pcolormesh(
907 overlay_cube[member.coord(stamp_coordinate).points[0]],
908 cmap=over_cmap,
909 norm=over_norm,
910 alpha=0.6,
911 vmin=over_vmin,
912 vmax=over_vmax,
913 )
914 # Overplot contour field, if required
915 if contour_cube: 915 ↛ 916line 915 didn't jump to line 916 because the condition on line 915 was never true
916 iplt.contour(
917 contour_cube[member.coord(stamp_coordinate).points[0]],
918 colors="darkgray",
919 levels=cntr_levels,
920 norm=cntr_norm,
921 alpha=0.6,
922 linestyles="--",
923 linewidths=1,
924 )
925 mtitle = _set_postage_stamp_title(member.coord(stamp_coordinate))
926 axes.set_title(f"{mtitle}")
928 # Put the shared colorbar in its own axes.
929 colorbar_axes = fig.add_axes([0.15, 0.05, 0.7, 0.03])
930 colorbar = fig.colorbar(
931 plot, colorbar_axes, orientation="horizontal", pad=0.042, shrink=0.7
932 )
933 colorbar.set_label(f"{cube.name()} ({cube.units})", size=14)
935 # Overall figure title.
936 fig.suptitle(title, fontsize=16)
938 # Save plot.
939 _save_close_figure(fig, "contour postate stamp", filename)
942def _plot_and_save_line_series(
943 cubes: iris.cube.CubeList,
944 coords: list[iris.coords.Coord],
945 ensemble_coord: str,
946 filename: str,
947 title: str,
948 **kwargs,
949):
950 """Plot and save a 1D line series.
952 Parameters
953 ----------
954 cubes: Cube or CubeList
955 Cube or CubeList containing the cubes to plot on the y-axis.
956 coords: list[Coord]
957 Coordinates to plot on the x-axis, one per cube.
958 ensemble_coord: str
959 Ensemble coordinate in the cube.
960 filename: str
961 Filename of the plot to write.
962 title: str
963 Plot title.
964 """
965 fig = plt.figure(figsize=(10, 10), facecolor="w", edgecolor="k")
967 model_colors_map = get_model_colors_map(cubes)
969 # Store min/max ranges.
970 y_levels = []
972 # Check match-up across sequence coords gives consistent sizes
973 validate_cubes_coords(cubes, coords)
975 for cube, coord in zip(cubes, coords, strict=True):
976 label = None
977 color = "black"
978 if model_colors_map:
979 label = cube.attributes.get("model_name")
980 color = model_colors_map.get(label)
981 if not cube.coords(ensemble_coord): 981 ↛ 983line 981 didn't jump to line 983 because the condition on line 981 was never true
982 # No ensemble coordinate — plot the cube directly as a single line.
983 iplt.plot(coord, cube, color=color, marker="o", ls="-", lw=3, label=label)
984 else:
985 for cube_slice in cube.slices_over(ensemble_coord):
986 # Label with (control) if part of an ensemble or not otherwise.
987 if cube_slice.coord(ensemble_coord).points == [0]:
988 iplt.plot(
989 coord,
990 cube_slice,
991 color=color,
992 marker="o",
993 ls="-",
994 lw=3,
995 label=f"{label} (control)"
996 if len(cube.coord(ensemble_coord).points) > 1
997 else label,
998 )
999 # Label with (perturbed) if part of an ensemble and not the control.
1000 else:
1001 iplt.plot(
1002 coord,
1003 cube_slice,
1004 color=color,
1005 ls="-",
1006 lw=1.5,
1007 alpha=0.75,
1008 label=f"{label} (member)",
1009 )
1011 # Calculate the global min/max if multiple cubes are given.
1012 _, levels, _ = colorbar_map_levels(cube, axis="y")
1013 if levels is not None: 1013 ↛ 1014line 1013 didn't jump to line 1014 because the condition on line 1013 was never true
1014 y_levels.append(min(levels))
1015 y_levels.append(max(levels))
1017 # Get the current axes.
1018 ax = plt.gca()
1020 # Add some labels and tweak the style.
1021 # check if cubes[0] works for single cube if not CubeList
1022 if coords[0].name() == "time":
1023 ax.set_xlabel(f"{coords[0].name()}", fontsize=14)
1024 else:
1025 ax.set_xlabel(f"{coords[0].name()} / {coords[0].units}", fontsize=14)
1026 ax.set_ylabel(f"{cubes[0].name()} / {cubes[0].units}", fontsize=14)
1027 ax.set_title(title, fontsize=16)
1029 ax.ticklabel_format(axis="y", useOffset=False)
1030 ax.tick_params(axis="x", labelrotation=15)
1031 ax.tick_params(axis="both", labelsize=12)
1033 # Set y limits to global min and max, autoscale if colorbar doesn't exist.
1034 if y_levels: 1034 ↛ 1035line 1034 didn't jump to line 1035 because the condition on line 1034 was never true
1035 ax.set_ylim(min(y_levels), max(y_levels))
1036 logger.debug("Line plot with y-axis limits %s-%s", min(y_levels), max(y_levels))
1037 else:
1038 ax.autoscale()
1040 # Add gridlines
1041 ax.grid(linestyle="--", color="grey", linewidth=1)
1042 # Add zero line
1043 ymin, ymax = ax.get_ylim()
1044 if ymin < 0.0 and ymax > 0.0:
1045 ax.axhline(y=0, xmin=0, xmax=1, ls="-", color="grey", lw=2)
1046 # Identify unique labels for legend
1047 handles = list(
1048 {
1049 label: handle
1050 for (handle, label) in zip(*ax.get_legend_handles_labels(), strict=True)
1051 }.values()
1052 )
1053 ax.legend(handles=handles, loc="best", ncol=1, frameon=True, fontsize=16)
1055 # Save plot.
1056 _save_close_figure(fig, "line", filename)
1059def _plot_and_save_line_power_spectrum_series(
1060 cubes: iris.cube.Cube | iris.cube.CubeList,
1061 coords: list[iris.coords.Coord],
1062 ensemble_coord: str,
1063 filename: str,
1064 title: str,
1065 series_coordinate: str,
1066 **kwargs,
1067):
1068 """Plot and save a 1D line series.
1070 Parameters
1071 ----------
1072 cubes: Cube or CubeList
1073 Cube or CubeList containing the cubes to plot on the y-axis.
1074 coords: list[Coord]
1075 Coordinates to plot on the x-axis, one per cube.
1076 ensemble_coord: str
1077 Ensemble coordinate in the cube.
1078 filename: str
1079 Filename of the plot to write.
1080 title: str
1081 Plot title.
1082 series_coordinate: str
1083 Coordinate being plotted on x-axis. In case of spectra frequency, physical_wavenumber, or wavelength.
1084 """
1085 fig = plt.figure(figsize=(10, 10), facecolor="w", edgecolor="k")
1086 model_colors_map = get_model_colors_map(cubes)
1087 ax = plt.gca()
1089 # Store min/max ranges.
1090 y_levels = []
1092 line_marker = None
1093 line_width = 1
1095 for cube in iter_maybe(cubes):
1096 # next 2 lines replace chunk of code.
1097 xcoord = _select_series_coord(cube, series_coordinate)
1098 xname = xcoord.points
1100 yfield = cube.data # power spectrum
1102 # If data from power spectra is all np.nans (like T+0h rainfall field which
1103 # might be full of zeros), then set yfield to zeros so it doesn't crash the
1104 # plotting.
1105 if np.all(np.isnan(yfield)):
1106 yfield = np.zeros_like(yfield)
1108 label = None
1109 color = "black"
1110 if model_colors_map: 1110 ↛ 1113line 1110 didn't jump to line 1113 because the condition on line 1110 was always true
1111 label = cube.attributes.get("model_name")
1112 color = model_colors_map.get(label)
1113 for cube_slice in cube.slices_over(ensemble_coord):
1114 # Label with (control) if part of an ensemble or not otherwise.
1115 if cube_slice.coord(ensemble_coord).points == [0]: 1115 ↛ 1129line 1115 didn't jump to line 1129 because the condition on line 1115 was always true
1116 ax.plot(
1117 xname,
1118 yfield,
1119 color=color,
1120 marker=line_marker,
1121 ls="-",
1122 lw=line_width,
1123 label=f"{label} (control)"
1124 if len(cube.coord(ensemble_coord).points) > 1
1125 else label,
1126 )
1127 # Label with (perturbed) if part of an ensemble and not the control.
1128 else:
1129 ax.plot(
1130 xname,
1131 yfield,
1132 color=color,
1133 ls="-",
1134 lw=1.5,
1135 alpha=0.75,
1136 label=f"{label} (member)",
1137 )
1139 # Calculate the global min/max if multiple cubes are given.
1140 _, levels, _ = colorbar_map_levels(cube, axis="y")
1141 if levels is not None: 1141 ↛ 1142line 1141 didn't jump to line 1142 because the condition on line 1141 was never true
1142 y_levels.append(min(levels))
1143 y_levels.append(max(levels))
1145 # Add some labels and tweak the style.
1147 title = f"{title}"
1148 ax.set_title(title, fontsize=16)
1150 # Set appropriate x-axis label based on coordinate
1151 if series_coordinate == "wavelength" or ( 1151 ↛ 1154line 1151 didn't jump to line 1154 because the condition on line 1151 was never true
1152 hasattr(xcoord, "long_name") and xcoord.long_name == "wavelength"
1153 ):
1154 ax.set_xlabel("Wavelength (km)", fontsize=14)
1155 elif series_coordinate == "physical_wavenumber" or ( 1155 ↛ 1158line 1155 didn't jump to line 1158 because the condition on line 1155 was never true
1156 hasattr(xcoord, "long_name") and xcoord.long_name == "physical_wavenumber"
1157 ):
1158 ax.set_xlabel("Wavenumber (km⁻¹)", fontsize=14)
1159 else: # frequency or check units
1160 if hasattr(xcoord, "units") and str(xcoord.units) == "km-1": 1160 ↛ 1161line 1160 didn't jump to line 1161 because the condition on line 1160 was never true
1161 ax.set_xlabel("Wavenumber (km⁻¹)", fontsize=14)
1162 else:
1163 ax.set_xlabel("Wavenumber", fontsize=14)
1165 ax.set_ylabel("Power Spectral Density", fontsize=14)
1166 ax.tick_params(axis="both", labelsize=12)
1168 # Set y limits to global min and max, autoscale if colorbar doesn't exist.
1170 # Set log-log scale
1171 ax.set_xscale("log")
1172 ax.set_yscale("log")
1174 # Add gridlines
1175 ax.grid(linestyle="--", color="grey", linewidth=1)
1176 # Ientify unique labels for legend
1177 handles = list(
1178 {
1179 label: handle
1180 for (handle, label) in zip(*ax.get_legend_handles_labels(), strict=True)
1181 }.values()
1182 )
1183 ax.legend(handles=handles, loc="best", ncol=1, frameon=True, fontsize=16)
1185 # Save plot.
1186 _save_close_figure(fig, "line power spectrum", filename)
1189def _plot_and_save_vertical_line_series(
1190 cubes: iris.cube.CubeList,
1191 coords: list[iris.coords.Coord],
1192 ensemble_coord: str,
1193 filename: str,
1194 series_coordinate: str,
1195 title: str,
1196 vmin: float,
1197 vmax: float,
1198 **kwargs,
1199):
1200 """Plot and save a 1D line series in vertical.
1202 Parameters
1203 ----------
1204 cubes: CubeList
1205 1 dimensional Cube or CubeList of the data to plot on x-axis.
1206 coord: list[Coord]
1207 Coordinates to plot on the y-axis, one per cube.
1208 ensemble_coord: str
1209 Ensemble coordinate in the cube.
1210 filename: str
1211 Filename of the plot to write.
1212 series_coordinate: str
1213 Coordinate to use as vertical axis.
1214 title: str
1215 Plot title.
1216 vmin: float
1217 Minimum value for the x-axis.
1218 vmax: float
1219 Maximum value for the x-axis.
1220 """
1221 # plot the vertical pressure axis using log scale
1222 fig = plt.figure(figsize=(10, 10), facecolor="w", edgecolor="k")
1224 model_colors_map = get_model_colors_map(cubes)
1226 # Check match-up across sequence coords gives consistent sizes
1227 validate_cubes_coords(cubes, coords)
1229 for cube, coord in zip(cubes, coords, strict=True):
1230 label = None
1231 color = "black"
1232 if model_colors_map: 1232 ↛ 1233line 1232 didn't jump to line 1233 because the condition on line 1232 was never true
1233 label = cube.attributes.get("model_name")
1234 color = model_colors_map.get(label)
1236 for cube_slice in cube.slices_over(ensemble_coord):
1237 # If ensemble data given plot control member with (control)
1238 # unless single forecast.
1239 if cube_slice.coord(ensemble_coord).points == [0]:
1240 iplt.plot(
1241 cube_slice,
1242 coord,
1243 color=color,
1244 marker="o",
1245 ls="-",
1246 lw=3,
1247 label=f"{label} (control)"
1248 if len(cube.coord(ensemble_coord).points) > 1
1249 else label,
1250 )
1251 # If ensemble data given plot perturbed members with (perturbed).
1252 else:
1253 iplt.plot(
1254 cube_slice,
1255 coord,
1256 color=color,
1257 ls="-",
1258 lw=1.5,
1259 alpha=0.75,
1260 label=f"{label} (member)",
1261 )
1263 # Get the current axis
1264 ax = plt.gca()
1266 # Special handling for pressure level data.
1267 if series_coordinate == "pressure": 1267 ↛ 1289line 1267 didn't jump to line 1289 because the condition on line 1267 was always true
1268 # Invert y-axis and set to log scale.
1269 ax.invert_yaxis()
1270 ax.set_yscale("log")
1272 # Define y-ticks and labels for pressure log axis.
1273 y_tick_labels = [
1274 "1000",
1275 "850",
1276 "700",
1277 "500",
1278 "300",
1279 "200",
1280 "100",
1281 ]
1282 y_ticks = [1000, 850, 700, 500, 300, 200, 100]
1284 # Set y-axis limits and ticks.
1285 ax.set_ylim(1100, 100)
1287 # Test if series_coordinate is model level data. The UM data uses
1288 # model_level_number and lfric uses full_levels as coordinate.
1289 elif series_coordinate in ("model_level_number", "full_levels", "half_levels"):
1290 # Define y-ticks and labels for vertical axis.
1291 y_ticks = iter_maybe(cubes)[0].coord(series_coordinate).points
1292 y_tick_labels = [str(int(i)) for i in y_ticks]
1293 ax.set_ylim(min(y_ticks), max(y_ticks))
1295 ax.set_yticks(y_ticks)
1296 ax.set_yticklabels(y_tick_labels)
1298 # Set x-axis limits.
1299 ax.set_xlim(vmin, vmax)
1300 # Mark y=0 if present in plot.
1301 if vmin < 0.0 and vmax > 0.0: 1301 ↛ 1302line 1301 didn't jump to line 1302 because the condition on line 1301 was never true
1302 ax.axvline(x=0, ymin=0, ymax=1, ls="-", color="grey", lw=2)
1304 # Add some labels and tweak the style.
1305 ax.set_ylabel(f"{coord.name()} / {coord.units}", fontsize=14)
1306 ax.set_xlabel(
1307 f"{iter_maybe(cubes)[0].name()} / {iter_maybe(cubes)[0].units}", fontsize=14
1308 )
1309 ax.set_title(title, fontsize=16)
1310 ax.ticklabel_format(axis="x")
1311 ax.tick_params(axis="y")
1312 ax.tick_params(axis="both", labelsize=12)
1314 # Add gridlines
1315 ax.grid(linestyle="--", color="grey", linewidth=1)
1316 # Ientify unique labels for legend
1317 handles = list(
1318 {
1319 label: handle
1320 for (handle, label) in zip(*ax.get_legend_handles_labels(), strict=True)
1321 }.values()
1322 )
1323 ax.legend(handles=handles, loc="best", ncol=1, frameon=True, fontsize=16)
1325 # Save plot.
1326 _save_close_figure(fig, "vertical line", filename)
1329def _plot_and_save_scatter_plot(
1330 cube_x: iris.cube.Cube | iris.cube.CubeList,
1331 cube_y: iris.cube.Cube | iris.cube.CubeList,
1332 filename: str,
1333 title: str,
1334 one_to_one: bool,
1335 model_names: list[str] | None = None,
1336 **kwargs,
1337):
1338 """Plot and save a 2D scatter plot.
1340 Parameters
1341 ----------
1342 cube_x: Cube | CubeList
1343 1 dimensional Cube or CubeList of the data to plot on x-axis.
1344 cube_y: Cube | CubeList
1345 1 dimensional Cube or CubeList of the data to plot on y-axis.
1346 filename: str
1347 Filename of the plot to write.
1348 title: str
1349 Plot title.
1350 one_to_one: bool
1351 Whether a 1:1 line is plotted.
1352 """
1353 fig = plt.figure(figsize=(10, 10), facecolor="w", edgecolor="k")
1354 # plot the cube_x and cube_y 1D fields as a scatter plot. If they are CubeLists this ensures
1355 # to pair each cube from cube_x with the corresponding cube from cube_y, allowing to iterate
1356 # over the pairs simultaneously.
1358 # Ensure cube_x and cube_y are iterable
1359 cube_x_iterable = iter_maybe(cube_x)
1360 cube_y_iterable = iter_maybe(cube_y)
1362 for cube_x_iter, cube_y_iter in zip(cube_x_iterable, cube_y_iterable, strict=True):
1363 iplt.scatter(cube_x_iter, cube_y_iter)
1364 if one_to_one is True:
1365 plt.plot(
1366 [
1367 np.nanmin([np.nanmin(cube_y.data), np.nanmin(cube_x.data)]),
1368 np.nanmax([np.nanmax(cube_y.data), np.nanmax(cube_x.data)]),
1369 ],
1370 [
1371 np.nanmin([np.nanmin(cube_y.data), np.nanmin(cube_x.data)]),
1372 np.nanmax([np.nanmax(cube_y.data), np.nanmax(cube_x.data)]),
1373 ],
1374 "k",
1375 linestyle="--",
1376 )
1377 ax = plt.gca()
1379 # Add some labels and tweak the style.
1380 if model_names is None:
1381 ax.set_xlabel(f"{cube_x[0].name()} / {cube_x[0].units}", fontsize=14)
1382 ax.set_ylabel(f"{cube_y[0].name()} / {cube_y[0].units}", fontsize=14)
1383 else:
1384 # Add the model names, these should be order of base (x) and other (y).
1385 ax.set_xlabel(
1386 f"{model_names[0]}_{cube_x[0].name()} / {cube_x[0].units}", fontsize=14
1387 )
1388 ax.set_ylabel(
1389 f"{model_names[1]}_{cube_y[0].name()} / {cube_y[0].units}", fontsize=14
1390 )
1391 ax.set_title(title, fontsize=16)
1392 ax.ticklabel_format(axis="y", useOffset=False)
1393 ax.tick_params(axis="x", labelrotation=15)
1394 ax.tick_params(axis="both", labelsize=12)
1395 ax.autoscale()
1397 # Save plot.
1398 _save_close_figure(fig, "scatter", filename)
1401def _plot_and_save_vector_plot(
1402 cube_u: iris.cube.Cube,
1403 cube_v: iris.cube.Cube,
1404 filename: str,
1405 title: str,
1406 method: Literal["contourf", "pcolormesh"],
1407 **kwargs,
1408):
1409 """Plot and save a 2D vector plot.
1411 Parameters
1412 ----------
1413 cube_u: Cube
1414 2 dimensional Cube of u component of the data.
1415 cube_v: Cube
1416 2 dimensional Cube of v component of the data.
1417 filename: str
1418 Filename of the plot to write.
1419 title: str
1420 Plot title.
1421 """
1422 fig = plt.figure(figsize=(10, 10), facecolor="w", edgecolor="k")
1423 # Create a cube containing the magnitude of the vector field.
1424 cube_vec_mag = (cube_u**2 + cube_v**2) ** 0.5
1425 cube_vec_mag.rename(f"{cube_u.long_name}_{cube_v.long_name}_magnitude")
1426 if "eastward_wind" in cube_u.long_name and "northward_wind" in cube_v.long_name:
1427 cube_vec_mag.rename(
1428 "wind_speed" + cube_u.long_name.replace("eastward_wind", "")
1429 )
1431 # Specify the color bar
1432 cmap, levels, norm = colorbar_map_levels(cube_vec_mag)
1434 # Setup plot map projection, extent and coastlines and borderlines.
1435 axes = _setup_spatial_map(cube_vec_mag, fig, cmap)
1437 if method == "contourf":
1438 # Filled contour plot of the field.
1439 plot = iplt.contourf(cube_vec_mag, cmap=cmap, levels=levels, norm=norm)
1440 elif method == "pcolormesh":
1441 try:
1442 vmin = min(levels)
1443 vmax = max(levels)
1444 except TypeError:
1445 vmin, vmax = None, None
1446 # pcolormesh plot of the field and ensure to use norm and not vmin/vmax
1447 # if levels are defined.
1448 if norm is not None:
1449 vmin = None
1450 vmax = None
1451 plot = iplt.pcolormesh(cube_vec_mag, cmap=cmap, norm=norm, vmin=vmin, vmax=vmax)
1452 else:
1453 raise ValueError(f"Unknown plotting method: {method}")
1455 # Check to see if transect, and if so, adjust y axis.
1456 if is_transect(cube_vec_mag):
1457 if "pressure" in [coord.name() for coord in cube_vec_mag.coords()]:
1458 axes.invert_yaxis()
1459 axes.set_yscale("log")
1460 axes.set_ylim(1100, 100)
1461 # If both model_level_number and level_height exists, iplt can construct
1462 # plot as a function of height above orography (NOT sea level).
1463 elif {"model_level_number", "level_height"}.issubset(
1464 {coord.name() for coord in cube_vec_mag.coords()}
1465 ):
1466 axes.set_yscale("log")
1468 axes.set_title(
1469 f"{title}\n"
1470 f"Start Lat: {cube_vec_mag.attributes['transect_coords'].split('_')[0]}"
1471 f" Start Lon: {cube_vec_mag.attributes['transect_coords'].split('_')[1]}"
1472 f" End Lat: {cube_vec_mag.attributes['transect_coords'].split('_')[2]}"
1473 f" End Lon: {cube_vec_mag.attributes['transect_coords'].split('_')[3]}",
1474 fontsize=16,
1475 )
1477 else:
1478 # Add title.
1479 axes.set_title(title, fontsize=16)
1481 # Add watermark with min/max/mean. Currently not user togglable.
1482 # In the bbox dictionary, fc and ec are hex colour codes for grey shade.
1483 cube_min, cube_max, cube_mean = calc_array_stats(cube_vec_mag.data)
1484 axes.annotate(
1485 f"Min: {cube_min:.3g} Max: {cube_max:.3g} Mean: {cube_mean:.3g}",
1486 xy=(0.05, -0.05),
1487 xycoords="axes fraction",
1488 xytext=(-5, 5),
1489 textcoords="offset points",
1490 ha="right",
1491 va="bottom",
1492 size=11,
1493 bbox={"boxstyle": "round", "fc": "#cccccc", "ec": "#808080", "alpha": 0.9},
1494 )
1496 # Add colour bar.
1497 cbar = fig.colorbar(plot, orientation="horizontal", pad=0.042, shrink=0.7)
1498 cbar.set_label(label=f"{cube_vec_mag.name()} ({cube_vec_mag.units})", size=14)
1499 # add ticks and tick_labels for every levels if less than 20 levels exist
1500 if levels is not None and len(levels) < 20:
1501 cbar.set_ticks(levels)
1502 cbar.set_ticklabels([f"{level:.1f}" for level in levels])
1504 # 30 barbs along the longest axis of the plot, or a barb per point for data
1505 # with less than 30 points.
1506 step = max(max(cube_u.shape) // 30, 1)
1507 iplt.quiver(cube_u[::step, ::step], cube_v[::step, ::step], pivot="middle")
1509 # Save plot.
1510 _save_close_figure(fig, "vector", filename)
1513def _plot_and_save_histogram_series(
1514 cubes: iris.cube.Cube | iris.cube.CubeList,
1515 filename: str,
1516 title: str,
1517 vmin: float,
1518 vmax: float,
1519 **kwargs,
1520):
1521 """Plot and save a histogram series.
1523 Parameters
1524 ----------
1525 cubes: Cube or CubeList
1526 2 dimensional Cube or CubeList of the data to plot as histogram.
1527 filename: str
1528 Filename of the plot to write.
1529 title: str
1530 Plot title.
1531 vmin: float
1532 minimum for colorbar
1533 vmax: float
1534 maximum for colorbar
1535 """
1536 fig = plt.figure(figsize=(10, 10), facecolor="w", edgecolor="k")
1537 ax = plt.gca()
1539 model_colors_map = get_model_colors_map(cubes)
1541 # Set default that histograms will produce probability density function
1542 # at each bin (integral over range sums to 1).
1543 density = True
1545 for cube in iter_maybe(cubes):
1546 # Easier to check title (where var name originates)
1547 # than seeing if long names exist etc.
1548 # Exception case, where distribution better fits log scales/bins.
1549 if (
1550 ("surface_microphysical" in title)
1551 or ("rain accumulation" in title)
1552 or ("Rainfall rate Composite" in title)
1553 or ("Nimrod_5min" in title)
1554 ):
1555 if "amount" in title:
1556 # Compute histogram following Klingaman et al. (2017): ASoP
1557 bin2 = np.exp(np.log(0.02) + 0.1 * np.linspace(0, 99, 100))
1558 bins = np.pad(bin2, (1, 0), "constant", constant_values=0)
1559 density = False
1560 else:
1561 bins = 10.0 ** (
1562 np.arange(-10, 27, 1) / 10.0
1563 ) # Suggestion from RMED toolbox.
1564 bins = np.insert(bins, 0, 0)
1565 ax.set_yscale("log")
1566 vmin = bins[1]
1567 vmax = bins[-1] # Manually set vmin/vmax to override json derived value.
1568 ax.set_xscale("log")
1569 elif "lightning" in title:
1570 bins = [0, 1, 2, 3, 4, 5]
1571 else:
1572 bins = np.linspace(vmin, vmax, 51)
1573 logger.debug(
1574 "Plotting histogram with %s bins %s - %s.",
1575 np.size(bins),
1576 np.min(bins),
1577 np.max(bins),
1578 )
1580 # Reshape cube data into a single array to allow for a single histogram.
1581 # Otherwise we plot xdim histograms stacked.
1582 cube_data_1d = (cube.data).flatten()
1584 label = None
1585 color = "black"
1586 if model_colors_map:
1587 label = cube.attributes.get("model_name")
1588 color = model_colors_map[label]
1589 x, y = np.histogram(cube_data_1d, bins=bins, density=density)
1591 # Compute area under curve.
1592 if (
1593 ("surface_microphysical" in title and "amount" in title)
1594 or ("rain_accumulation" in title)
1595 or ("Rainfall rate Composite" in title)
1596 or ("Nimrod_5min" in title)
1597 ):
1598 bin_mean = (bins[:-1] + bins[1:]) / 2.0
1599 x = x * bin_mean / x.sum()
1600 x = x[1:]
1601 y = y[1:]
1603 ax.plot(
1604 y[:-1], x, color=color, linewidth=3, marker="o", markersize=6, label=label
1605 )
1607 # Add some labels and tweak the style.
1608 ax.set_title(title, fontsize=16)
1609 ax.set_xlabel(
1610 f"{iter_maybe(cubes)[0].name()} / {iter_maybe(cubes)[0].units}", fontsize=14
1611 )
1612 ax.set_ylabel("Normalised probability density", fontsize=14)
1613 if (
1614 ("surface_microphysical" in title and "amount" in title)
1615 or ("rain accumulation" in title)
1616 or ("Nimrod_5min" in title)
1617 ):
1618 ax.set_ylabel(
1619 f"Contribution to mean ({iter_maybe(cubes)[0].units})", fontsize=14
1620 )
1621 try:
1622 ax.set_xlim(vmin, vmax)
1623 except ValueError:
1624 pass
1625 ax.tick_params(axis="both", labelsize=12)
1627 # Overlay grid-lines onto histogram plot.
1628 ax.grid(linestyle="--", color="grey", linewidth=1)
1629 if model_colors_map:
1630 ax.legend(loc="best", ncol=1, frameon=True, fontsize=16)
1632 # Save plot.
1633 _save_close_figure(fig, "histogram", filename)
1636def _plot_and_save_postage_stamp_histogram_series(
1637 cube: iris.cube.Cube,
1638 filename: str,
1639 title: str,
1640 stamp_coordinate: str,
1641 vmin: float,
1642 vmax: float,
1643 **kwargs,
1644):
1645 """Plot and save postage (ensemble members) stamps for a histogram series.
1647 Parameters
1648 ----------
1649 cube: Cube
1650 2 dimensional Cube of the data to plot as histogram.
1651 filename: str
1652 Filename of the plot to write.
1653 title: str
1654 Plot title.
1655 stamp_coordinate: str
1656 Coordinate that becomes different plots.
1657 vmin: float
1658 minimum for pdf x-axis
1659 vmax: float
1660 maximum for pdf x-axis
1661 """
1662 # Use the smallest square grid that will fit the members.
1663 nmember = len(cube.coord(stamp_coordinate).points)
1664 grid_rows = int(math.sqrt(nmember))
1665 grid_size = math.ceil(nmember / grid_rows)
1667 fig = plt.figure(
1668 figsize=(10, 10 * max(grid_rows / grid_size, 0.5)), facecolor="w", edgecolor="k"
1669 )
1670 # Make a subplot for each member.
1671 for member, subplot in zip(
1672 cube.slices_over(stamp_coordinate),
1673 range(1, grid_size * grid_rows + 1),
1674 strict=False,
1675 ):
1676 # Implicit interface is much easier here, due to needing to have the
1677 # cartopy GeoAxes generated.
1678 plt.subplot(grid_rows, grid_size, subplot)
1679 # Reshape cube data into a single array to allow for a single histogram.
1680 # Otherwise we plot xdim histograms stacked.
1681 member_data_1d = (member.data).flatten()
1682 plt.hist(member_data_1d, density=True, stacked=True)
1683 axes = plt.gca()
1684 mtitle = _set_postage_stamp_title(member.coord(stamp_coordinate))
1685 axes.set_title(f"{mtitle}")
1686 axes.set_xlim(vmin, vmax)
1688 # Overall figure title.
1689 fig.suptitle(title, fontsize=16)
1691 # Save plot.
1692 _save_close_figure(fig, "histogram postage stamp", filename)
1695def _plot_and_save_postage_stamps_in_single_plot_histogram_series(
1696 cube: iris.cube.Cube,
1697 filename: str,
1698 title: str,
1699 stamp_coordinate: str,
1700 vmin: float,
1701 vmax: float,
1702 **kwargs,
1703):
1704 fig, ax = plt.subplots(figsize=(10, 10), facecolor="w", edgecolor="k")
1705 ax.set_title(title, fontsize=16)
1706 ax.set_xlim(vmin, vmax)
1707 ax.set_xlabel(f"{cube.name()} / {cube.units}", fontsize=14)
1708 ax.set_ylabel("normalised probability density", fontsize=14)
1709 # Loop over all slices along the stamp_coordinate
1710 for member in cube.slices_over(stamp_coordinate):
1711 # Flatten the member data to 1D
1712 member_data_1d = member.data.flatten()
1713 # Plot the histogram using plt.hist
1714 mtitle = _set_postage_stamp_title(member.coord(stamp_coordinate))
1715 plt.hist(
1716 member_data_1d,
1717 density=True,
1718 stacked=True,
1719 label=f"{mtitle}",
1720 )
1722 # Add a legend
1723 ax.legend(fontsize=16)
1725 # Save plot.
1726 _save_close_figure(fig, "histogram postage stamp", filename)
1729def _plot_and_save_scatter_series(
1730 cubes: iris.cube.Cube | iris.cube.CubeList,
1731 filename: str,
1732 title: str,
1733 vmin: float,
1734 vmax: float,
1735 hexbin: bool,
1736 **kwargs,
1737):
1738 """Plot and save a scatter plot series.
1740 Parameters
1741 ----------
1742 cubes: Cube or CubeList
1743 2 dimensional Cube or CubeList of the data to plot as scatter.
1744 filename: str
1745 Filename of the plot to write.
1746 title: str
1747 Plot title.
1748 vmin: float
1749 minimum for colorbar
1750 vmax: float
1751 maximum for colorbar
1752 hexbin: bool
1753 Flag to set output scatter generated as a hexbin frequency distribution plot of 2 cubes on single plot.
1754 Else scatter of all points, with potential to overplot many comparisons on same plot.
1755 """
1756 if hexbin:
1757 # Check cubes using same functionality as the difference operator.
1758 if len(cubes) != 2:
1759 raise ValueError(
1760 "Cubes should contain exactly 2 cubes for hexbin plotting."
1761 )
1762 title = title.replace("scatter", "hexbin")
1763 filename = filename.replace("scatter", "hexbin")
1765 fig = plt.figure(figsize=(10, 10), facecolor="w", edgecolor="k")
1766 ax = plt.gca()
1768 model_colors_map = get_model_colors_map(cubes)
1770 percentiles = np.arange(0, 100, 5)
1771 percentiles[0] = 1
1772 percentiles[-1] = 99
1773 quantiles = iris.cube.CubeList()
1775 # Loop through all output cubes for both data points and overplotting quantiles.
1776 # Set indexing of nplot to avoid plotting 1:1 scatter of cubes[0] vs cubes[0]
1777 for plottype in ["points", "quantiles"]:
1778 nplot = 0
1779 for cube in iter_maybe(cubes):
1780 label = None
1781 color = "black"
1782 if model_colors_map: 1782 ↛ 1787line 1782 didn't jump to line 1787 because the condition on line 1782 was always true
1783 label = cube.attributes.get("model_name")
1784 color = model_colors_map[label]
1786 # Plot all data points
1787 if plottype == "points":
1788 if nplot > 0:
1789 if hexbin:
1790 hb = plt.hexbin(
1791 cubes[0].data.flatten(),
1792 cube.data.flatten(),
1793 alpha=0.3,
1794 gridsize=100,
1795 mincnt=1,
1796 )
1797 else:
1798 plt.scatter(
1799 cubes[0].data.flatten(),
1800 cube.data.flatten(),
1801 color=color,
1802 marker="+",
1803 label=None,
1804 alpha=0.3,
1805 )
1807 elif plottype == "quantiles": 1807 ↛ 1826line 1807 didn't jump to line 1826 because the condition on line 1807 was always true
1808 # Construct Q-Q plot
1809 quantiles.append(
1810 cube.collapsed(
1811 cube.coords(dim_coords=True),
1812 iris.analysis.PERCENTILE,
1813 percent=percentiles,
1814 )
1815 )
1816 if nplot > 0:
1817 iplt.scatter(
1818 quantiles[0],
1819 quantiles[-1],
1820 color=color,
1821 marker="o",
1822 label=label,
1823 edgecolors="black",
1824 )
1826 nplot = nplot + 1
1828 # Add some labels and tweak the style.
1829 ax.set_title(title, fontsize=16)
1830 ax.set_xlabel(
1831 f"{iter_maybe(cubes)[0].name()} / {iter_maybe(cubes)[0].units}", fontsize=14
1832 )
1833 ax.set_ylabel(
1834 f"{iter_maybe(cubes)[1].name()} / {iter_maybe(cubes)[1].units}", fontsize=14
1835 )
1836 ax.tick_params(axis="both", labelsize=12)
1837 ax.autoscale()
1839 # Set 1:1 line and equal axes if scatter plot of common cube names
1840 nameA = iter_maybe(cubes)[0].name()
1841 nameB = iter_maybe(cubes)[1].name()
1842 if any(part in nameB.split("_") for part in nameA.split("_")): 1842 ↛ 1853line 1842 didn't jump to line 1853 because the condition on line 1842 was always true
1843 lims = [
1844 np.min([ax.get_xlim(), ax.get_ylim()]), # min of both axes
1845 np.max([ax.get_xlim(), ax.get_ylim()]), # max of both axes
1846 ]
1847 ax.plot(lims, lims, "k-", alpha=0.75, zorder=0)
1848 ax.set_aspect("equal")
1849 ax.set_xlim(lims)
1850 ax.set_ylim(lims)
1852 # Overlay grid-lines onto scatter plot.
1853 ax.grid(linestyle="--", color="grey", linewidth=1)
1854 if model_colors_map: 1854 ↛ 1858line 1854 didn't jump to line 1858 because the condition on line 1854 was always true
1855 ax.legend(loc="upper left", ncol=1, frameon=True, fontsize=16)
1857 # Add colorbar if hexbin output
1858 if hexbin:
1859 cb = plt.colorbar(
1860 hb, orientation="horizontal", location="bottom", pad=0.08, shrink=0.7
1861 )
1862 cb.set_label("Number of data points", size=12)
1864 # Save plot.
1865 _save_close_figure(fig, "scatter", filename)
1868def _spatial_plot(
1869 method: Literal["contourf", "pcolormesh", "scatter"],
1870 cube: iris.cube.Cube,
1871 filename: str | None,
1872 sequence_coordinate: str,
1873 stamp_coordinate: str,
1874 overlay_cube: iris.cube.Cube | None = None,
1875 contour_cube: iris.cube.Cube | None = None,
1876 point_cube: iris.cube.Cube | None = None,
1877 **kwargs,
1878):
1879 """Plot a spatial variable onto a map from a 2D, 3D, or 4D cube.
1881 A 2D spatial field can be plotted, but if the sequence_coordinate is present
1882 then a sequence of plots will be produced. Similarly if the stamp_coordinate
1883 is present then postage stamp plots will be produced.
1885 If any optional overlay_cube, contour_cube or point_cube are specified, multiple data layers can
1886 be overplotted on the same figure.
1888 Parameters
1889 ----------
1890 method: "contourf" | "pcolormesh" | "scatter"
1891 The plotting method to use.
1892 Select choice of "contourf" or "pcolormesh" for gridded data.
1893 Use "scatter" for point-based data.
1894 cube: Cube
1895 Iris cube of the data to plot. It should have two spatial dimensions,
1896 such as lat and lon, and may also have a another two dimension to be
1897 plotted sequentially and/or as postage stamp plots.
1898 filename: str | None
1899 Name of the plot to write, used as a prefix for plot sequences. If None
1900 uses the recipe name.
1901 sequence_coordinate: str
1902 Coordinate about which to make a plot sequence. Defaults to ``"time"``.
1903 This coordinate must exist in the cube.
1904 stamp_coordinate: str
1905 Coordinate about which to plot postage stamp plots. Defaults to
1906 ``"realization"``.
1907 overlay_cube: Cube | None, optional
1908 Optional 2 dimensional (lat and lon) Cube of data to overplot on top of base cube
1909 contour_cube: Cube | None, optional
1910 Optional 2 dimensional (lat and lon) Cube of data to overplot as contours over base cube
1911 point_cube: Cube | None, optional
1912 Optional 1 dimensional (e.g. list of points) or 2 dimensional (lat and lon) Cube of data to overplot as map of scatter points over base cube
1914 Raises
1915 ------
1916 ValueError
1917 If the cube doesn't have the right dimensions.
1918 TypeError
1919 If the cube isn't a single cube.
1920 """
1921 # Ensure we've got a single cube.
1922 cube = check_single_cube(cube)
1924 # Set title based on recipe metadata or use cube name
1925 recipe_title = get_recipe_metadata().get("title", cube.name())
1927 # Check if there is a valid stamp coordinate in cube dimensions.
1928 if stamp_coordinate == "realization": 1928 ↛ 1933line 1928 didn't jump to line 1933 because the condition on line 1928 was always true
1929 stamp_coordinate = check_stamp_coordinate(cube)
1931 # Make postage stamp plots if stamp_coordinate exists and has more than a
1932 # single point.
1933 plotting_func = _plot_and_save_spatial_plot
1934 try:
1935 if cube.coord(stamp_coordinate).shape[0] > 1:
1936 plotting_func = _plot_and_save_postage_stamp_spatial_plot
1937 except iris.exceptions.CoordinateNotFoundError:
1938 pass
1940 # Produce a geographical scatter plot if the data have a
1941 # dimension called observation or model_obs_error
1942 if any(
1943 crd.var_name == "station"
1944 or crd.var_name == "Station_Name"
1945 or crd.var_name == "model_obs_error"
1946 for crd in cube.coords()
1947 ):
1948 plotting_func = _plot_and_save_spatial_plot
1949 method = "scatter"
1951 # Must have a sequence coordinate.
1952 try:
1953 cube.coord(sequence_coordinate)
1954 except iris.exceptions.CoordinateNotFoundError as err:
1955 raise ValueError(f"Cube must have a {sequence_coordinate} coordinate.") from err
1957 # Create a plot for each value of the sequence coordinate.
1958 plot_index = []
1959 nplot = np.size(cube.coord(sequence_coordinate).points)
1961 for iseq, cube_slice in enumerate(cube.slices_over(sequence_coordinate)):
1962 # Set plot titles and filename
1963 seq_coord = cube_slice.coord(sequence_coordinate)
1965 if "model_name" in cube.attributes: 1965 ↛ 1966line 1965 didn't jump to line 1966 because the condition on line 1965 was never true
1966 model_name = cube.attributes["model_name"]
1967 else:
1968 model_name = None
1970 plot_title, plot_filename = _set_title_and_filename(
1971 seq_coord, nplot, recipe_title, filename, model_name=model_name
1972 )
1974 # Extract sequence slice for overlay_cube, contour_cube and point_cube if required.
1975 overlay_slice = slice_over_maybe(overlay_cube, sequence_coordinate, iseq)
1976 contour_slice = slice_over_maybe(contour_cube, sequence_coordinate, iseq)
1977 point_slice = slice_over_maybe(point_cube, sequence_coordinate, iseq)
1979 # Do the actual plotting.
1980 plotting_func(
1981 cube_slice,
1982 filename=plot_filename,
1983 stamp_coordinate=stamp_coordinate,
1984 title=plot_title,
1985 method=method,
1986 overlay_cube=overlay_slice,
1987 contour_cube=contour_slice,
1988 point_cube=point_slice,
1989 **kwargs,
1990 )
1991 plot_index.append(plot_filename)
1993 # Add list of plots to plot metadata.
1994 complete_plot_index = _append_to_plot_index(plot_index)
1996 # Make a page to display the plots.
1997 _make_plot_html_page(complete_plot_index)
2000####################
2001# Public functions #
2002####################
2005def spatial_contour_plot(
2006 cube: iris.cube.Cube,
2007 filename: str | None = None,
2008 sequence_coordinate: str = "time",
2009 stamp_coordinate: str = "realization",
2010 **kwargs,
2011) -> iris.cube.Cube:
2012 """Plot a spatial variable onto a map from a 2D, 3D, or 4D cube.
2014 A 2D spatial field can be plotted, but if the sequence_coordinate is present
2015 then a sequence of plots will be produced. Similarly if the stamp_coordinate
2016 is present then postage stamp plots will be produced.
2018 Parameters
2019 ----------
2020 cube: Cube
2021 Iris cube of the data to plot. It should have two spatial dimensions,
2022 such as lat and lon, and may also have a another two dimension to be
2023 plotted sequentially and/or as postage stamp plots.
2024 filename: str, optional
2025 Name of the plot to write, used as a prefix for plot sequences. Defaults
2026 to the recipe name.
2027 sequence_coordinate: str, optional
2028 Coordinate about which to make a plot sequence. Defaults to ``"time"``.
2029 This coordinate must exist in the cube.
2030 stamp_coordinate: str, optional
2031 Coordinate about which to plot postage stamp plots. Defaults to
2032 ``"realization"``.
2034 Returns
2035 -------
2036 Cube
2037 The original cube (so further operations can be applied).
2039 Raises
2040 ------
2041 ValueError
2042 If the cube doesn't have the right dimensions.
2043 TypeError
2044 If the cube isn't a single cube.
2045 """
2046 _spatial_plot(
2047 "contourf", cube, filename, sequence_coordinate, stamp_coordinate, **kwargs
2048 )
2049 return cube
2052def spatial_pcolormesh_plot(
2053 cubes: iris.cube.Cube | iris.cube.CubeList,
2054 filename: str | None = None,
2055 sequence_coordinate: str = "time",
2056 stamp_coordinate: str = "realization",
2057 **kwargs,
2058) -> iris.cube.Cube:
2059 """Plot a spatial variable onto a map from a 2D, 3D, or 4D cube.
2061 A 2D spatial field can be plotted, but if the sequence_coordinate is present
2062 then a sequence of plots will be produced. Similarly if the stamp_coordinate
2063 is present then postage stamp plots will be produced.
2065 This function is significantly faster than ``spatial_contour_plot``,
2066 especially at high resolutions, and should be preferred unless contiguous
2067 contour areas are important.
2069 Parameters
2070 ----------
2071 cube: Cubes
2072 Iris cube or cubelist of the data to plot. Each cube should have two spatial dimensions,
2073 such as lat and lon, and may also have a another two dimension to be
2074 plotted sequentially and/or as postage stamp plots.
2075 filename: str, optional
2076 Name of the plot to write, used as a prefix for plot sequences. Defaults
2077 to the recipe name.
2078 sequence_coordinate: str, optional
2079 Coordinate about which to make a plot sequence. Defaults to ``"time"``.
2080 This coordinate must exist in the cube.
2081 stamp_coordinate: str, optional
2082 Coordinate about which to plot postage stamp plots. Defaults to
2083 ``"realization"``.
2085 Returns
2086 -------
2087 Cubes
2088 The original cube/cubelist (so further operations can be applied).
2090 Raises
2091 ------
2092 ValueError
2093 If the cube doesn't have the right dimensions.
2094 """
2095 if isinstance(cubes, iris.cube.CubeList): 2095 ↛ 2096line 2095 didn't jump to line 2096 because the condition on line 2095 was never true
2096 for model_cube in cubes:
2097 _spatial_plot(
2098 "pcolormesh",
2099 model_cube,
2100 filename,
2101 sequence_coordinate,
2102 stamp_coordinate,
2103 **kwargs,
2104 )
2105 elif isinstance(cubes, iris.cube.Cube): 2105 ↛ 2114line 2105 didn't jump to line 2114 because the condition on line 2105 was always true
2106 _spatial_plot(
2107 "pcolormesh",
2108 cubes,
2109 filename,
2110 sequence_coordinate,
2111 stamp_coordinate,
2112 **kwargs,
2113 )
2114 return cubes
2117def spatial_multi_pcolormesh_plot(
2118 cube: iris.cube.Cube,
2119 overlay_cube: iris.cube.Cube | None = None,
2120 contour_cube: iris.cube.Cube | None = None,
2121 point_cube: iris.cube.Cube | None = None,
2122 filename: str | None = None,
2123 sequence_coordinate: str = "time",
2124 stamp_coordinate: str = "realization",
2125 **kwargs,
2126) -> iris.cube.Cube:
2127 """Plot a set of spatial variables onto a map from a 2D, 3D, or 4D cube.
2129 A 2D basis cube spatial field can be plotted, but if the sequence_coordinate is present
2130 then a sequence of plots will be produced. Similarly if the stamp_coordinate
2131 is present then postage stamp plots will be produced.
2133 If specified, a masked overlay_cube can be overplotted on top of the base cube.
2135 If specified, contours of a contour_cube can be overplotted on top of those.
2137 If specified, a spatial scatter map of point_cube can be overplotted.
2139 For single-variable equivalent of this routine, use spatial_pcolormesh_plot.
2141 This function is significantly faster than ``spatial_contour_plot``,
2142 especially at high resolutions, and should be preferred unless contiguous
2143 contour areas are important.
2145 Parameters
2146 ----------
2147 cube: Cube
2148 Iris cube of the data to plot. It should have two spatial dimensions,
2149 such as lat and lon, and may also have two additional dimensions to be
2150 plotted sequentially and/or as postage stamp plots.
2151 overlay_cube: Cube, optional
2152 Iris cube of the data to plot as an overlay on top of basis cube. It should have two spatial dimensions,
2153 such as lat and lon, and may also have two additional dimensions to be
2154 plotted sequentially and/or as postage stamp plots. This is likely to be a masked cube in order not to hide the underlying basis cube.
2155 If not provided, output plot generated without overlay cube.
2156 contour_cube: Cube, optional
2157 Iris cube of the data to plot as a contour overlay on top of basis cube (and overlay_cube). It should have two spatial dimensions,
2158 such as lat and lon, and may also have two additional dimensions to be
2159 plotted sequentially and/or as postage stamp plots. If not provided, output plot generated without contours.
2160 point_cube: Cube, optional
2161 Iris cube of the data to plot as a scatter map overlay on top of basis cube (overlay_cube and/or contour_cube). It should have two
2162 spatial dimensions, such as lat and lon, but these can describe a 1-D cube (e.g. list of
2163 observation stations with lat/lon coordinates) and may also have two additional dimensions to be plotted sequentially and/or as
2164 postage stamp plots. If not provided, output plot generated without point-based layer.
2165 filename: str, optional
2166 Name of the plot to write, used as a prefix for plot sequences. Defaults
2167 to the recipe name.
2168 sequence_coordinate: str, optional
2169 Coordinate about which to make a plot sequence. Defaults to ``"time"``.
2170 This coordinate must exist in the cube.
2171 stamp_coordinate: str, optional
2172 Coordinate about which to plot postage stamp plots. Defaults to
2173 ``"realization"``.
2175 Returns
2176 -------
2177 Cube
2178 The original cube (so further operations can be applied).
2180 Raises
2181 ------
2182 ValueError
2183 If the cube doesn't have the right dimensions.
2184 TypeError
2185 If the cube isn't a single cube.
2186 """
2187 _spatial_plot(
2188 "pcolormesh",
2189 cube,
2190 filename,
2191 sequence_coordinate,
2192 stamp_coordinate,
2193 overlay_cube=overlay_cube,
2194 contour_cube=contour_cube,
2195 point_cube=point_cube,
2196 )
2197 return cube, overlay_cube, contour_cube, point_cube
2200# TODO: Expand function to handle ensemble data.
2201# line_coordinate: str, optional
2202# Coordinate about which to plot multiple lines. Defaults to
2203# ``"realization"``.
2204def plot_line_series(
2205 cube: iris.cube.Cube | iris.cube.CubeList,
2206 filename: str | None = None,
2207 series_coordinate: str = "time",
2208 sequence_coordinate: str = "time",
2209 # add the following for ensembles
2210 stamp_coordinate: str = "realization",
2211 single_plot: bool = False,
2212 **kwargs,
2213) -> iris.cube.Cube | iris.cube.CubeList:
2214 """Plot a line plot for the specified coordinate.
2216 The Cube or CubeList must be 1D.
2218 Parameters
2219 ----------
2220 iris.cube | iris.cube.CubeList
2221 Cube or CubeList of the data to plot. The individual cubes should have a single dimension.
2222 The cubes should cover the same phenomenon i.e. all cubes contain temperature data.
2223 We do not support different data such as temperature and humidity in the same CubeList for plotting.
2224 filename: str, optional
2225 Name of the plot to write, used as a prefix for plot sequences. Defaults
2226 to the recipe name.
2227 series_coordinate: str, optional
2228 Coordinate about which to make a series. Defaults to ``"time"``. This
2229 coordinate must exist in the cube.
2231 Returns
2232 -------
2233 iris.cube.Cube | iris.cube.CubeList
2234 The original Cube or CubeList (so further operations can be applied).
2236 Raises
2237 ------
2238 ValueError
2239 If the cubes don't have the right dimensions.
2240 TypeError
2241 If the cube isn't a Cube or CubeList.
2242 """
2243 # Ensure we have a name for the plot file.
2244 recipe_title = get_recipe_metadata().get("title", iter_maybe(cube)[0].name())
2246 num_models = get_num_models(cube)
2248 validate_cube_shape(cube, num_models)
2250 # Iterate over all cubes and extract coordinate to plot.
2251 cubes = iris.cube.CubeList(iter_maybe(cube))
2252 coords = []
2253 for model_cube in cubes:
2254 try:
2255 coords.append(model_cube.coord(series_coordinate))
2256 except iris.exceptions.CoordinateNotFoundError as err:
2257 raise ValueError(
2258 f"Cube must have a {series_coordinate} coordinate."
2259 ) from err
2260 # Count dimensions excluding realization
2261 ndim = model_cube.ndim
2263 if model_cube.coords("realization"): 2263 ↛ 2270line 2263 didn't jump to line 2270 because the condition on line 2263 was always true
2264 realization_dims = model_cube.coord_dims("realization")
2266 # Only subtract if realization is a dimension coordinate
2267 if realization_dims:
2268 ndim -= len(realization_dims)
2270 if ndim > 2:
2271 raise ValueError(
2272 "Cube must be 1D or 2D (excluding any realization dimension)."
2273 )
2275 plot_index = []
2277 # Check if this is a spectral plot by looking for spectral coordinates
2278 is_spectral_plot = series_coordinate in [
2279 "frequency",
2280 "physical_wavenumber",
2281 "wavelength",
2282 ]
2284 if is_spectral_plot:
2285 # If series coordinate is frequency, physical_wavenumber or wavelength, for example power spectra with series
2286 # coordinate frequency/wavenumber.
2287 # If several power spectra are plotted with time as sequence_coordinate for the
2288 # time slider option.
2290 # Internal plotting function.
2291 plotting_func = _plot_and_save_line_power_spectrum_series
2293 for model_cube in cubes:
2294 try:
2295 model_cube.coord(sequence_coordinate)
2296 except iris.exceptions.CoordinateNotFoundError as err:
2297 raise ValueError(
2298 f"Cube must have a {sequence_coordinate} coordinate."
2299 ) from err
2301 if num_models == 1: 2301 ↛ 2316line 2301 didn't jump to line 2316 because the condition on line 2301 was always true
2302 # check for ensembles
2303 if ( 2303 ↛ 2307line 2303 didn't jump to line 2307 because the condition on line 2303 was never true
2304 stamp_coordinate in [c.name() for c in cubes[0].coords()]
2305 and cubes[0].coord(stamp_coordinate).shape[0] > 1
2306 ):
2307 if single_plot:
2308 # Plot spectra, mean and ensemble spread on 1 plot
2309 plotting_func = _plot_and_save_postage_stamps_in_single_plot_power_spectrum_series
2310 else:
2311 # Plot postage stamps
2312 plotting_func = _plot_and_save_postage_stamp_power_spectrum_series
2313 cube_iterables = cubes[0].slices_over(sequence_coordinate)
2314 nplot = np.size(cubes[0].coord(sequence_coordinate).points)
2315 else:
2316 all_points = sorted(
2317 set(
2318 itertools.chain.from_iterable(
2319 cb.coord(sequence_coordinate).points for cb in cubes
2320 )
2321 )
2322 )
2323 all_slices = list(
2324 itertools.chain.from_iterable(
2325 cb.slices_over(sequence_coordinate) for cb in cubes
2326 )
2327 )
2328 # Matched slices (matched by seq coord point; it may happen that
2329 # evaluated models do not cover the same seq coord range, hence matching
2330 # necessary)
2331 cube_iterables = [
2332 iris.cube.CubeList(
2333 s
2334 for s in all_slices
2335 if s.coord(sequence_coordinate).points[0] == point
2336 )
2337 for point in all_points
2338 ]
2339 nplot = len(all_points)
2341 # Create a plot for each value of the sequence coordinate. Allowing for
2342 # multiple cubes in a CubeList to be plotted in the same plot for similar
2343 # sequence values. Passing a CubeList into the internal plotting function
2344 # for similar values of the sequence coordinate. cube_slice can be an
2345 # iris.cube.Cube or an iris.cube.CubeList.
2347 for cube_slice in cube_iterables:
2348 # Normalize cube_slice to a list of cubes
2349 if isinstance(cube_slice, iris.cube.CubeList): 2349 ↛ 2350line 2349 didn't jump to line 2350 because the condition on line 2349 was never true
2350 cubes = list(cube_slice)
2351 elif isinstance(cube_slice, iris.cube.Cube): 2351 ↛ 2354line 2351 didn't jump to line 2354 because the condition on line 2351 was always true
2352 cubes = [cube_slice]
2353 else:
2354 raise TypeError(f"Expected Cube or CubeList, got {type(cube_slice)}")
2356 # Use sequence value so multiple sequences can merge.
2357 seq_coord = cube_slice[0].coord(sequence_coordinate)
2358 plot_title, plot_filename = _set_title_and_filename(
2359 seq_coord, nplot, recipe_title, filename
2360 )
2362 # Format the coordinate value in a unit appropriate way.
2363 title = f"{recipe_title}\n [{seq_coord.units.title(seq_coord.points[0])}]"
2365 # Use sequence (e.g. time) bounds if plotting single non-sequence outputs
2366 if nplot == 1 and seq_coord.has_bounds and np.size(seq_coord.bounds) > 1: 2366 ↛ 2367line 2366 didn't jump to line 2367 because the condition on line 2366 was never true
2367 title = f"{recipe_title}\n [{seq_coord.units.title(seq_coord.bounds[0][0])} to {seq_coord.units.title(seq_coord.bounds[0][1])}]"
2369 # Do the actual plotting.
2370 plotting_func(
2371 cube_slice,
2372 coords,
2373 stamp_coordinate,
2374 plot_filename,
2375 title,
2376 series_coordinate,
2377 )
2379 plot_index.append(plot_filename)
2380 else:
2381 # Format the title and filename using plotted series coordinate
2382 nplot = 1
2383 seq_coord = coords[0]
2384 plot_title, plot_filename = _set_title_and_filename(
2385 seq_coord, nplot, recipe_title, filename
2386 )
2388 # Treat cubes with station coordinate as point observation timeseries, looping over available points
2389 if (
2390 "station" in [c.name() for c in cubes[0].coords()]
2391 and len(cubes[0].coord("station").points) > 1
2392 ):
2393 for station in cubes[0].coord("station").points:
2394 station_cubes = cubes.extract(iris.Constraint(station=station))
2395 station_name = station_cubes[0].coord("Station_Name").points[0]
2396 station_plotname = plot_filename.replace(
2397 ".png", "_" + station_name + ".png"
2398 )
2399 _plot_and_save_line_series(
2400 station_cubes,
2401 coords,
2402 "realization",
2403 station_plotname,
2404 f"{plot_title} {station_name}",
2405 )
2406 plot_index.append(station_plotname)
2408 else:
2409 # Do the actual plotting for all other series coordinate options.
2410 _plot_and_save_line_series(
2411 cubes, coords, stamp_coordinate, plot_filename, plot_title
2412 )
2414 plot_index.append(plot_filename)
2416 # append plot to list of plots
2417 complete_plot_index = _append_to_plot_index(plot_index)
2419 # Make a page to display the plots.
2420 _make_plot_html_page(complete_plot_index)
2422 return cube
2425def plot_vertical_line_series(
2426 cubes: iris.cube.Cube | iris.cube.CubeList,
2427 filename: str | None = None,
2428 series_coordinate: str = "model_level_number",
2429 sequence_coordinate: str = "time",
2430 # line_coordinate: str = "realization",
2431 **kwargs,
2432) -> iris.cube.Cube | iris.cube.CubeList:
2433 """Plot a line plot against a type of vertical coordinate.
2435 The Cube or CubeList must be 1D.
2437 A 1D line plot with y-axis as pressure coordinate can be plotted, but if the sequence_coordinate is present
2438 then a sequence of plots will be produced.
2440 Parameters
2441 ----------
2442 iris.cube | iris.cube.CubeList
2443 Cube or CubeList of the data to plot. The individual cubes should have a single dimension.
2444 The cubes should cover the same phenomenon i.e. all cubes contain temperature data.
2445 We do not support different data such as temperature and humidity in the same CubeList for plotting.
2446 filename: str, optional
2447 Name of the plot to write, used as a prefix for plot sequences. Defaults
2448 to the recipe name.
2449 series_coordinate: str, optional
2450 Coordinate to plot on the y-axis. Can be ``pressure`` or
2451 ``model_level_number`` for UM, or ``full_levels`` or ``half_levels``
2452 for LFRic. Defaults to ``model_level_number``.
2453 This coordinate must exist in the cube.
2454 sequence_coordinate: str, optional
2455 Coordinate about which to make a plot sequence. Defaults to ``"time"``.
2456 This coordinate must exist in the cube.
2458 Returns
2459 -------
2460 iris.cube.Cube | iris.cube.CubeList
2461 The original Cube or CubeList (so further operations can be applied).
2462 Plotted data.
2464 Raises
2465 ------
2466 ValueError
2467 If the cubes doesn't have the right dimensions.
2468 TypeError
2469 If the cube isn't a Cube or CubeList.
2470 """
2471 # Ensure we have a name for the plot file.
2472 recipe_title = get_recipe_metadata().get("title", iter_maybe(cubes)[0].name())
2474 cubes = iter_maybe(cubes)
2475 # Initialise empty list to hold all data from all cubes in a CubeList
2476 all_data = []
2478 # Store min/max ranges for x range.
2479 x_levels = []
2481 num_models = get_num_models(cubes)
2483 validate_cube_shape(cubes, num_models)
2485 # Iterate over all cubes in cube or CubeList and plot.
2486 coords = []
2487 for cube in cubes:
2488 # Test if series coordinate i.e. pressure level exist for any cube with cube.ndim >=1.
2489 try:
2490 coords.append(cube.coord(series_coordinate))
2491 except iris.exceptions.CoordinateNotFoundError as err:
2492 raise ValueError(
2493 f"Cube must have a {series_coordinate} coordinate."
2494 ) from err
2496 try:
2497 if cube.ndim > 1 or not cube.coords("realization"): 2497 ↛ 2505line 2497 didn't jump to line 2505 because the condition on line 2497 was always true
2498 cube.coord(sequence_coordinate)
2499 except iris.exceptions.CoordinateNotFoundError as err:
2500 raise ValueError(
2501 f"Cube must have a {sequence_coordinate} coordinate or be 1D, or 2D with a realization coordinate."
2502 ) from err
2504 # Get minimum and maximum from levels information.
2505 _, levels, _ = colorbar_map_levels(cube, axis="x")
2506 if levels is not None: 2506 ↛ 2510line 2506 didn't jump to line 2510 because the condition on line 2506 was always true
2507 x_levels.append(min(levels))
2508 x_levels.append(max(levels))
2509 else:
2510 all_data.append(cube.data)
2512 if len(x_levels) == 0: 2512 ↛ 2514line 2512 didn't jump to line 2514 because the condition on line 2512 was never true
2513 # Combine all data into a single NumPy array
2514 combined_data = np.concatenate(all_data)
2516 # Set the lower and upper limit for the x-axis to ensure all plots have
2517 # same range. This needs to read the whole cube over the range of the
2518 # sequence and if applicable postage stamp coordinate.
2519 vmin = np.floor(combined_data.min())
2520 vmax = np.ceil(combined_data.max())
2521 else:
2522 vmin = min(x_levels)
2523 vmax = max(x_levels)
2525 # Check if the cube has a sequence coordinate (e.g. time). If not, plot
2526 # a single profile directly without iterating over a sequence.
2527 sequence_coords = [
2528 cube.coord(sequence_coordinate)
2529 for cube in cubes
2530 if cube.coords(sequence_coordinate)
2531 ]
2532 has_sequence_coord = len(sequence_coords) == len(cubes) and all(
2533 np.size(coord.points) > 1 for coord in sequence_coords
2534 )
2535 has_scalar_sequence_coord = len(sequence_coords) == len(cubes) and all(
2536 np.size(coord.points) == 1 for coord in sequence_coords
2537 )
2539 plot_index = []
2540 if has_sequence_coord: 2540 ↛ 2565line 2540 didn't jump to line 2565 because the condition on line 2540 was always true
2541 # Matching the slices (matching by seq coord point; it may happen that
2542 # evaluated models do not cover the same seq coord range, hence matching
2543 # necessary)
2544 cube_iterables = _find_matched_slices(cubes, sequence_coordinate)
2545 nplot = np.size(cubes[0].coord(sequence_coordinate).points)
2546 for cubes_slice in cube_iterables:
2547 # Format the coordinate value in a unit appropriate way.
2548 seq_coord = cubes_slice[0].coord(sequence_coordinate)
2549 plot_title, plot_filename = _set_title_and_filename(
2550 seq_coord, nplot, recipe_title, filename
2551 )
2553 # Do the actual plotting.
2554 _plot_and_save_vertical_line_series(
2555 cubes_slice,
2556 coords,
2557 "realization",
2558 plot_filename,
2559 series_coordinate,
2560 title=plot_title,
2561 vmin=vmin,
2562 vmax=vmax,
2563 )
2564 plot_index.append(plot_filename)
2565 elif has_scalar_sequence_coord:
2566 # Scalar sequence coordinate (typically aggregated time bounds):
2567 # make one plot and include sequence period in title/filename.
2568 plot_title, plot_filename = _set_title_and_filename(
2569 sequence_coords[0], 1, recipe_title, filename
2570 )
2572 _plot_and_save_vertical_line_series(
2573 cubes,
2574 coords,
2575 "realization",
2576 plot_filename,
2577 series_coordinate,
2578 title=plot_title,
2579 vmin=vmin,
2580 vmax=vmax,
2581 )
2582 plot_index.append(plot_filename)
2583 else:
2584 # 1D case: no sequence coordinate, plot a single profile.
2585 plot_title = recipe_title
2586 if filename:
2587 plot_filename = filename
2588 else:
2589 plot_filename = f"{slugify(plot_title)}.png"
2591 _plot_and_save_vertical_line_series(
2592 cubes,
2593 coords,
2594 "realization",
2595 plot_filename,
2596 series_coordinate,
2597 title=plot_title,
2598 vmin=vmin,
2599 vmax=vmax,
2600 )
2601 plot_index.append(plot_filename)
2603 # Add list of plots to plot metadata.
2604 complete_plot_index = _append_to_plot_index(plot_index)
2606 # Make a page to display the plots.
2607 _make_plot_html_page(complete_plot_index)
2609 return cubes
2612def qq_plot(
2613 cubes: iris.cube.CubeList,
2614 coordinates: list[str],
2615 percentiles: list[float],
2616 model_names: list[str],
2617 filename: str | None = None,
2618 one_to_one: bool = True,
2619 **kwargs,
2620) -> iris.cube.CubeList:
2621 """Plot a Quantile-Quantile plot between two models for common time points.
2623 The cubes will be normalised by collapsing each cube to its percentiles. Cubes are
2624 collapsed within the operator over all specified coordinates such as
2625 grid_latitude, grid_longitude, vertical levels, but also realisation representing
2626 ensemble members to ensure a 1D cube (array).
2628 Parameters
2629 ----------
2630 cubes: iris.cube.CubeList
2631 Two cubes of the same variable with different models.
2632 coordinate: list[str]
2633 The list of coordinates to collapse over. This list should be
2634 every coordinate within the cube to result in a 1D cube around
2635 the percentile coordinate.
2636 percent: list[float]
2637 A list of percentiles to appear in the plot.
2638 model_names: list[str]
2639 A list of model names to appear on the axis of the plot.
2640 filename: str, optional
2641 Filename of the plot to write.
2642 one_to_one: bool, optional
2643 If True a 1:1 line is plotted; if False it is not. Default is True.
2645 Raises
2646 ------
2647 ValueError
2648 When the cubes are not compatible.
2650 Notes
2651 -----
2652 The quantile-quantile plot is a variant on the scatter plot representing
2653 two datasets by their quantiles (percentiles) for common time points.
2654 This plot does not use a theoretical distribution to compare against, but
2655 compares percentiles of two datasets. This plot does
2656 not use all raw data points, but plots the selected percentiles (quantiles) of
2657 each variable instead for the two datasets, thereby normalising the data for a
2658 direct comparison between the selected percentiles of the two dataset distributions.
2660 Quantile-quantile plots are valuable for comparing against
2661 observations and other models. Identical percentiles between the variables
2662 will lie on the one-to-one line implying the values correspond well to each
2663 other. Where there is a deviation from the one-to-one line a range of
2664 possibilities exist depending on how and where the data is shifted (e.g.,
2665 Wilks 2011 [Wilks2011]_).
2667 For distributions above the one-to-one line the distribution is left-skewed;
2668 below is right-skewed. A distinct break implies a bimodal distribution, and
2669 closer values/values further apart at the tails imply poor representation of
2670 the extremes.
2672 """
2673 # Check cubes using same functionality as the difference operator.
2674 if len(cubes) != 2:
2675 raise ValueError("cubes should contain exactly 2 cubes.")
2676 base: Cube = cubes.extract_cube(iris.AttributeConstraint(cset_comparison_base=1))
2677 other: Cube = cubes.extract_cube(
2678 iris.Constraint(
2679 cube_func=lambda cube: "cset_comparison_base" not in cube.attributes
2680 )
2681 )
2683 # Get spatial coord names.
2684 base_lat_name, base_lon_name = get_cube_yxcoordname(base)
2685 other_lat_name, other_lon_name = get_cube_yxcoordname(other)
2687 # Ensure cubes to compare are on common differencing grid.
2688 # This is triggered if either
2689 # i) latitude and longitude shapes are not the same. Note grid points
2690 # are not compared directly as these can differ through rounding
2691 # errors.
2692 # ii) or variables are known to often sit on different grid staggering
2693 # in different models (e.g. cell center vs cell edge), as is the case
2694 # for UM and LFRic comparisons.
2695 # In future greater choice of regridding method might be applied depending
2696 # on variable type. Linear regridding can in general be appropriate for smooth
2697 # variables. Care should be taken with interpretation of differences
2698 # given this dependency on regridding.
2699 if (
2700 base.coord(base_lat_name).shape != other.coord(other_lat_name).shape
2701 or base.coord(base_lon_name).shape != other.coord(other_lon_name).shape
2702 ) or (
2703 base.long_name
2704 in [
2705 "eastward_wind_at_10m",
2706 "northward_wind_at_10m",
2707 "northward_wind_at_cell_centres",
2708 "eastward_wind_at_cell_centres",
2709 "zonal_wind_at_pressure_levels",
2710 "meridional_wind_at_pressure_levels",
2711 "potential_vorticity_at_pressure_levels",
2712 "vapour_specific_humidity_at_pressure_levels_for_climate_averaging",
2713 ]
2714 ):
2715 logger.debug("Linear regridding base cube to other grid to compute differences")
2716 base = regrid_onto_cube(base, other, method="Linear")
2718 # Extract just common time points.
2719 base, other = _extract_common_time_points(base, other)
2721 # Equalise attributes so we can merge.
2722 fully_equalise_attributes([base, other])
2723 logger.debug("Base: %s\nOther: %s", base, other)
2725 # Collapse cubes.
2726 base = collapse(
2727 base,
2728 coordinate=coordinates,
2729 method="PERCENTILE",
2730 additional_percent=percentiles,
2731 )
2732 other = collapse(
2733 other,
2734 coordinate=coordinates,
2735 method="PERCENTILE",
2736 additional_percent=percentiles,
2737 )
2739 # Ensure we have a name for the plot file.
2740 recipe_title = get_recipe_metadata().get("title", "QQ_plot")
2741 title = f"{recipe_title}"
2743 if filename is None:
2744 filename = slugify(recipe_title)
2746 # Add file extension.
2747 plot_filename = f"{filename.rsplit('.', 1)[0]}.png"
2749 # Do the actual plotting on a scatter plot
2750 _plot_and_save_scatter_plot(
2751 base, other, plot_filename, title, one_to_one, model_names
2752 )
2754 # Add list of plots to plot metadata.
2755 plot_index = _append_to_plot_index([plot_filename])
2757 # Make a page to display the plots.
2758 _make_plot_html_page(plot_index)
2760 return iris.cube.CubeList([base, other])
2763def hinton_plot(change, signif, xaxis_labels, yaxis_labels, magnitude=None):
2764 """
2765 Plot a Hinton style triangle/scorecard plot.
2767 This plot type can be useful for summarising high level information, such as comparing
2768 how 'skillful' two models are when verified against observations for a variety of metrics,
2769 as a function of lead-time. A few parameters of the plot style are fixed in function rather
2770 than customisable by the user as input arguments; many have been designed to automatically
2771 scale the plot depending on the number of x and y components.
2773 Parameters
2774 ----------
2775 change: np.ndarray
2776 A 2d numpy array containing the values (scaled to 1 to -1) that determine the triangle
2777 size/direction.
2778 signif: np.ndarray
2779 A 2d numpy array containing 0s and 1s to determine if triangle is significant or not.
2780 xaxis_labels: list
2781 List of labels for the xaxis (must match the second dimension length of signif and change,
2782 along with magnitude if not None).
2783 yaxis_labels: list
2784 List of labels for the yaxis (must match the first dimension length of signif and change,
2785 along with magnitude if not None).
2786 magnitude: np.ndarray | None
2787 Optional 2D array, matching the shape of change, signif, which contains numerical values
2788 the user wishes to display under each respective triangle.
2790 Returns
2791 -------
2792 matplotlib axes object to either display or do further modifications to.
2793 """
2794 # Setup colors of triangles
2795 color_pos = "#7CAE00"
2796 color_neg = "#7B68EE"
2798 # Setup cell/text size ratios
2799 figsize = None
2800 cell_size_in = 0.35
2801 text_row_ratio = 0.25
2803 # Ensure arrays, and change to bool for sig.
2804 change = np.asarray(change)
2805 signif = np.asarray(signif).astype(bool)
2806 if magnitude is not None: 2806 ↛ 2807line 2806 didn't jump to line 2807 because the condition on line 2806 was never true
2807 magnitude = np.asarray(magnitude)
2809 # Get the number of x and y elements
2810 ny, nx = change.shape
2812 # Build non-uniform y coordinates
2813 tri_height = 1.0
2814 txt_height = text_row_ratio
2816 tri_y = []
2817 txt_y = []
2818 y_edges = [0.0]
2820 y = 0.0
2821 for _j in range(ny):
2822 tri_y.append(y + tri_height / 2)
2823 y += tri_height
2824 y_edges.append(y)
2826 if magnitude is not None: 2826 ↛ 2827line 2826 didn't jump to line 2827 because the condition on line 2826 was never true
2827 txt_y.append(y + txt_height / 2)
2828 y += txt_height
2829 y_edges.append(y)
2831 total_height = y
2833 # Dynamic figure size
2834 if figsize is None: 2834 ↛ 2839line 2834 didn't jump to line 2839 because the condition on line 2834 was always true
2835 width = nx * cell_size_in
2836 height = total_height * cell_size_in + 2
2837 figsize = (width, height)
2839 fig, ax = plt.subplots(figsize=figsize)
2841 # Setup axes and grid.
2842 ax.set_aspect("equal", adjustable="box")
2843 ax.set_xlim(-0.5, nx - 0.5)
2844 ax.set_ylim(0, total_height)
2846 ax.set_xticks(np.arange(nx))
2847 ax.set_xticklabels(xaxis_labels, rotation=90)
2849 ax.set_yticks(tri_y)
2850 ax.set_yticklabels(yaxis_labels)
2852 ax.set_xticks(np.arange(-0.5, nx, 1), minor=True)
2853 ax.set_yticks(y_edges, minor=True)
2855 ax.set_axisbelow(True)
2856 ax.grid(which="minor", linestyle=":", linewidth=0.3, color="0.7")
2857 ax.grid(False, which="major")
2858 ax.tick_params(which="minor", length=0)
2860 ax.invert_yaxis()
2862 # Compute marker scaling (fixed overlap)
2863 fig.canvas.draw()
2865 bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
2866 width_in, height_in = bbox.width, bbox.height
2868 cell_w = (width_in * fig.dpi) / nx
2869 cell_h = (height_in * fig.dpi) / total_height
2870 cell_pixels = min(cell_w, cell_h)
2872 max_marker_size = (0.6 * cell_pixels) ** 2
2874 text_fontsize = cell_pixels * 0.15
2876 # Plot triangles + text
2877 for j in range(ny):
2878 for i in range(nx):
2879 val = change[j, i]
2880 if np.isnan(val): 2880 ↛ 2881line 2880 didn't jump to line 2881 because the condition on line 2880 was never true
2881 continue
2883 if abs(val) < 0.01: 2883 ↛ 2884line 2883 didn't jump to line 2884 because the condition on line 2883 was never true
2884 continue
2886 sig = signif[j, i]
2887 size = max_marker_size * abs(val)
2889 # Triangle style
2890 if val >= 0:
2891 marker = "^"
2892 color = color_pos
2893 else:
2894 marker = "v"
2895 color = color_neg
2897 if sig:
2898 edgecolor = "black"
2899 linewidth = 0.6
2900 else:
2901 edgecolor = "none"
2902 linewidth = 0.0
2904 # Triangle
2905 ax.scatter(
2906 i,
2907 tri_y[j],
2908 s=size,
2909 marker=marker,
2910 c=color,
2911 edgecolors=edgecolor,
2912 linewidths=linewidth,
2913 zorder=3,
2914 clip_on=True, # ensures no rendering bleed
2915 )
2917 # Text row
2918 if magnitude is not None: 2918 ↛ 2919line 2918 didn't jump to line 2919 because the condition on line 2918 was never true
2919 mag_val = magnitude[j, i]
2921 if not np.isnan(mag_val):
2922 ax.text(
2923 i,
2924 txt_y[j],
2925 f"{mag_val:.1f}",
2926 ha="center",
2927 va="center",
2928 fontsize=text_fontsize,
2929 color="black",
2930 zorder=4,
2931 )
2933 plt.tight_layout()
2934 return fig, ax
2937def scatter_plot(
2938 cube_x: iris.cube.Cube | iris.cube.CubeList,
2939 cube_y: iris.cube.Cube | iris.cube.CubeList,
2940 filename: str | None = None,
2941 one_to_one: bool = True,
2942 **kwargs,
2943) -> iris.cube.CubeList:
2944 """Plot a scatter plot between two variables.
2946 Both cubes must be 1D.
2948 Parameters
2949 ----------
2950 cube_x: Cube | CubeList
2951 1 dimensional Cube of the data to plot on y-axis.
2952 cube_y: Cube | CubeList
2953 1 dimensional Cube of the data to plot on x-axis.
2954 filename: str, optional
2955 Filename of the plot to write.
2956 one_to_one: bool, optional
2957 If True a 1:1 line is plotted; if False it is not. Default is True.
2959 Returns
2960 -------
2961 cubes: CubeList
2962 CubeList of the original x and y cubes for further processing.
2964 Raises
2965 ------
2966 ValueError
2967 If the cube doesn't have the right dimensions and cubes not the same
2968 size.
2969 TypeError
2970 If the cube isn't a single cube.
2972 Notes
2973 -----
2974 Scatter plots are used for determining if there is a relationship between
2975 two variables. Positive relations have a slope going from bottom left to top
2976 right; Negative relations have a slope going from top left to bottom right.
2977 """
2978 # Iterate over all cubes in cube or CubeList and plot.
2979 for cube_iter in iter_maybe(cube_x):
2980 # Check cubes are correct shape.
2981 cube_iter = check_single_cube(cube_iter)
2982 if cube_iter.ndim > 1:
2983 raise ValueError("cube_x must be 1D.")
2985 # Iterate over all cubes in cube or CubeList and plot.
2986 for cube_iter in iter_maybe(cube_y):
2987 # Check cubes are correct shape.
2988 cube_iter = check_single_cube(cube_iter)
2989 if cube_iter.ndim > 1:
2990 raise ValueError("cube_y must be 1D.")
2992 # Ensure we have a name for the plot file.
2993 recipe_title = get_recipe_metadata().get("title", "Scatter_plot")
2994 title = f"{recipe_title}"
2996 if filename is None:
2997 filename = slugify(recipe_title)
2999 # Add file extension.
3000 plot_filename = f"{filename.rsplit('.', 1)[0]}.png"
3002 # Do the actual plotting.
3003 _plot_and_save_scatter_plot(cube_x, cube_y, plot_filename, title, one_to_one)
3005 # Add list of plots to plot metadata.
3006 plot_index = _append_to_plot_index([plot_filename])
3008 # Make a page to display the plots.
3009 _make_plot_html_page(plot_index)
3011 return iris.cube.CubeList([cube_x, cube_y])
3014def vector_plot(
3015 cube_u: iris.cube.Cube,
3016 cube_v: iris.cube.Cube,
3017 filename: str | None = None,
3018 sequence_coordinate: str = "time",
3019 **kwargs,
3020) -> iris.cube.CubeList:
3021 """Plot a vector plot based on the input u and v components."""
3022 recipe_title = get_recipe_metadata().get("title", "Vector_plot")
3024 # Cubes must have a matching sequence coordinate.
3025 try:
3026 # Check that the u and v cubes have the same sequence coordinate.
3027 if cube_u.coord(sequence_coordinate) != cube_v.coord(sequence_coordinate): 3027 ↛ anywhereline 3027 didn't jump anywhere: it always raised an exception.
3028 raise ValueError("Coordinates do not match.")
3029 except (iris.exceptions.CoordinateNotFoundError, ValueError) as err:
3030 raise ValueError(
3031 f"Cubes should have matching {sequence_coordinate} coordinate:\n{cube_u}\n{cube_v}"
3032 ) from err
3034 # Create a plot for each value of the sequence coordinate.
3035 plot_index = []
3036 nplot = np.size(cube_u[0].coord(sequence_coordinate).points)
3037 for cube_u_slice, cube_v_slice in zip(
3038 cube_u.slices_over(sequence_coordinate),
3039 cube_v.slices_over(sequence_coordinate),
3040 strict=True,
3041 ):
3042 # Format the coordinate value in a unit appropriate way.
3043 seq_coord = cube_u_slice.coord(sequence_coordinate)
3044 plot_title, plot_filename = _set_title_and_filename(
3045 seq_coord, nplot, recipe_title, filename
3046 )
3048 # Do the actual plotting.
3049 _plot_and_save_vector_plot(
3050 cube_u_slice,
3051 cube_v_slice,
3052 filename=plot_filename,
3053 title=plot_title,
3054 method="pcolormesh",
3055 )
3056 plot_index.append(plot_filename)
3058 # Add list of plots to plot metadata.
3059 complete_plot_index = _append_to_plot_index(plot_index)
3061 # Make a page to display the plots.
3062 _make_plot_html_page(complete_plot_index)
3064 return iris.cube.CubeList([cube_u, cube_v])
3067def plot_histogram_series(
3068 cubes: iris.cube.Cube | iris.cube.CubeList,
3069 filename: str | None = None,
3070 sequence_coordinate: str = "time",
3071 stamp_coordinate: str = "realization",
3072 single_plot: bool = False,
3073 **kwargs,
3074) -> iris.cube.Cube | iris.cube.CubeList:
3075 """Plot a histogram plot for each vertical level provided.
3077 A histogram plot can be plotted, but if the sequence_coordinate (i.e. time)
3078 is present then a sequence of plots will be produced using the time slider
3079 functionality to scroll through histograms against time. If a
3080 stamp_coordinate is present then postage stamp plots will be produced. If
3081 stamp_coordinate and single_plot is True, all postage stamp plots will be
3082 plotted in a single plot instead of separate postage stamp plots.
3084 Parameters
3085 ----------
3086 cubes: Cube | iris.cube.CubeList
3087 Iris cube or CubeList of the data to plot. It should have a single dimension other
3088 than the stamp coordinate.
3089 The cubes should cover the same phenomenon i.e. all cubes contain temperature data.
3090 We do not support different data such as temperature and humidity in the same CubeList for plotting.
3091 filename: str, optional
3092 Name of the plot to write, used as a prefix for plot sequences. Defaults
3093 to the recipe name.
3094 sequence_coordinate: str, optional
3095 Coordinate about which to make a plot sequence. Defaults to ``"time"``.
3096 This coordinate must exist in the cube and will be used for the time
3097 slider.
3098 stamp_coordinate: str, optional
3099 Coordinate about which to plot postage stamp plots. Defaults to
3100 ``"realization"``.
3101 single_plot: bool, optional
3102 If True, all postage stamp plots will be plotted in a single plot. If
3103 False, each postage stamp plot will be plotted separately. Is only valid
3104 if stamp_coordinate exists and has more than a single point.
3106 Returns
3107 -------
3108 iris.cube.Cube | iris.cube.CubeList
3109 The original Cube or CubeList (so further operations can be applied).
3110 Plotted data.
3112 Raises
3113 ------
3114 ValueError
3115 If the cube doesn't have the right dimensions.
3116 TypeError
3117 If the cube isn't a Cube or CubeList.
3118 """
3119 recipe_title = get_recipe_metadata().get("title", "Histogram")
3121 cubes = iter_maybe(cubes)
3123 # Internal plotting function.
3124 plotting_func = _plot_and_save_histogram_series
3126 num_models = get_num_models(cubes)
3128 validate_cube_shape(cubes, num_models)
3130 # If several histograms are plotted, check sequence_coordinate
3131 check_sequence_coordinate(cubes, sequence_coordinate)
3133 # Get axis minimum and maximum from levels information.
3134 # If no levels set, derive minima and maxima from data in CubeList.
3135 vmin, vmax = _set_axis_range(cubes)
3137 # Make postage stamp plots if stamp_coordinate exists and has more than a
3138 # single point. If single_plot is True:
3139 # -- all postage stamp plots will be plotted in a single plot instead of
3140 # separate postage stamp plots.
3141 # -- model names (hidden in cube attrs) are ignored, that is stamp plots are
3142 # produced per single model only
3143 if num_models == 1:
3144 if ( 3144 ↛ 3148line 3144 didn't jump to line 3148 because the condition on line 3144 was never true
3145 stamp_coordinate in [c.name() for c in cubes[0].coords()]
3146 and cubes[0].coord(stamp_coordinate).shape[0] > 1
3147 ):
3148 if single_plot:
3149 plotting_func = (
3150 _plot_and_save_postage_stamps_in_single_plot_histogram_series
3151 )
3152 else:
3153 plotting_func = _plot_and_save_postage_stamp_histogram_series
3154 cube_iterables = cubes[0].slices_over(sequence_coordinate)
3155 else:
3156 cube_iterables = _find_matched_slices(cubes, sequence_coordinate)
3158 plot_index = []
3159 nplot = np.size(cubes[0].coord(sequence_coordinate).points)
3160 # Create a plot for each value of the sequence coordinate. Allowing for
3161 # multiple cubes in a CubeList to be plotted in the same plot for similar
3162 # sequence values. Passing a CubeList into the internal plotting function
3163 # for similar values of the sequence coordinate. cube_slice can be an
3164 # iris.cube.Cube or an iris.cube.CubeList.
3165 for cube_slice in cube_iterables:
3166 single_cube = cube_slice
3167 if isinstance(cube_slice, iris.cube.CubeList):
3168 single_cube = cube_slice[0]
3170 # Ensure valid stamp coordinate in cube dimensions
3171 if stamp_coordinate == "realization": 3171 ↛ 3174line 3171 didn't jump to line 3174 because the condition on line 3171 was always true
3172 stamp_coordinate = check_stamp_coordinate(single_cube)
3173 # Set plot titles and filename, based on sequence coordinate
3174 seq_coord = single_cube.coord(sequence_coordinate)
3175 # Use time coordinate in title and filename if single histogram output.
3176 if sequence_coordinate == "realization" and nplot == 1: 3176 ↛ 3177line 3176 didn't jump to line 3177 because the condition on line 3176 was never true
3177 seq_coord = single_cube.coord("time")
3178 # Use station name in title and filename if model vs obs comparison
3179 if sequence_coordinate == "station": 3179 ↛ 3180line 3179 didn't jump to line 3180 because the condition on line 3179 was never true
3180 seq_coord = single_cube.coord("Station_Name")
3182 plot_title, plot_filename = _set_title_and_filename(
3183 seq_coord, nplot, recipe_title, filename
3184 )
3186 # Do the actual plotting.
3187 plotting_func(
3188 cube_slice,
3189 filename=plot_filename,
3190 stamp_coordinate=stamp_coordinate,
3191 title=plot_title,
3192 vmin=vmin,
3193 vmax=vmax,
3194 )
3195 plot_index.append(plot_filename)
3197 # Add list of plots to plot metadata.
3198 complete_plot_index = _append_to_plot_index(plot_index)
3200 # Make a page to display the plots.
3201 _make_plot_html_page(complete_plot_index)
3203 return cubes
3206def plot_scatter_series(
3207 cubes: iris.cube.Cube | iris.cube.CubeList,
3208 filename: str | None = None,
3209 sequence_coordinate: str = "time",
3210 stamp_coordinate: str = "realization",
3211 hexbin: bool = False,
3212 **kwargs,
3213) -> iris.cube.Cube | iris.cube.CubeList:
3214 """Plot a scatter plot for each sequence coordinate provided.
3216 A scatter plot can be plotted, but if the sequence_coordinate (i.e. time)
3217 is present then a sequence of plots will be produced using the time slider
3218 functionality to scroll through scatter against time. If a
3219 stamp_coordinate is present then postage stamp plots will be produced. If
3220 stamp_coordinate and single_plot is True, all postage stamp plots will be
3221 plotted in a single plot instead of separate postage stamp plots.
3223 Parameters
3224 ----------
3225 cubes: Cube | iris.cube.CubeList
3226 Iris cube or CubeList of the data to plot. It should have a single dimension other
3227 than the stamp coordinate.
3228 The cubes should cover the same phenomenon i.e. all cubes contain temperature data.
3229 We do not support different data such as temperature and humidity in the same CubeList for plotting.
3230 filename: str, optional
3231 Name of the plot to write, used as a prefix for plot sequences. Defaults
3232 to the recipe name.
3233 sequence_coordinate: str, optional
3234 Coordinate about which to make a plot sequence. Defaults to ``"time"``.
3235 This coordinate must exist in the cube and will be used for the time
3236 slider.
3237 stamp_coordinate: str, optional
3238 Coordinate about which to plot postage stamp plots. Defaults to
3239 ``"realization"``.
3240 hexbin: bool, optional
3241 If True, generate hexbin comparison plot.
3242 If False, generate point-by-point scatter plot.
3244 Returns
3245 -------
3246 iris.cube.Cube | iris.cube.CubeList
3247 The original Cube or CubeList (so further operations can be applied).
3248 Plotted data.
3250 Raises
3251 ------
3252 ValueError
3253 If the cube doesn't have the right dimensions.
3254 TypeError
3255 If the cube isn't a Cube or CubeList.
3256 """
3257 recipe_title = get_recipe_metadata().get("title", "Scatter")
3259 cubes = iter_maybe(cubes)
3261 # Internal plotting function.
3262 plotting_func = _plot_and_save_scatter_series
3264 num_models = get_num_models(cubes)
3266 validate_cube_shape(cubes, num_models)
3268 check_sequence_coordinate(cubes, sequence_coordinate)
3270 vmin, vmax = _set_axis_range(cubes)
3272 # Require >1 models to compare on scatter plot
3273 if num_models > 1:
3274 cube_iterables = _find_matched_slices(cubes, sequence_coordinate)
3275 else:
3276 raise ValueError(
3277 "Scatter plot series requires multiple number of models in input data."
3278 )
3280 plot_index = []
3281 nplot = np.size(cubes[0].coord(sequence_coordinate).points)
3282 # Create a plot for each value of the sequence coordinate. Allowing for
3283 # multiple cubes in a CubeList to be plotted in the same plot for similar
3284 # sequence values. Passing a CubeList into the internal plotting function
3285 # for similar values of the sequence coordinate. cube_slice can be an
3286 # iris.cube.Cube or an iris.cube.CubeList.
3287 for cube_slice in cube_iterables:
3288 single_cube = cube_slice
3289 if isinstance(cube_slice, iris.cube.CubeList): 3289 ↛ 3293line 3289 didn't jump to line 3293 because the condition on line 3289 was always true
3290 single_cube = cube_slice[0]
3292 # Ensure valid stamp coordinate in cube dimensions
3293 if stamp_coordinate == "realization": 3293 ↛ 3296line 3293 didn't jump to line 3296 because the condition on line 3293 was always true
3294 stamp_coordinate = check_stamp_coordinate(single_cube)
3295 # Set plot titles and filename, based on sequence coordinate
3296 seq_coord = single_cube.coord(sequence_coordinate)
3297 # Use time coordinate in title and filename if single histogram output.
3298 if sequence_coordinate == "realization" and nplot == 1:
3299 seq_coord = single_cube.coord("time")
3300 # Use station name in title and filename if model vs obs comparison
3301 if sequence_coordinate == "station":
3302 seq_coord = single_cube.coord("Station_Name")
3304 plot_title, plot_filename = _set_title_and_filename(
3305 seq_coord, nplot, recipe_title, filename
3306 )
3308 # Do the actual plotting.
3309 plotting_func(
3310 cube_slice,
3311 filename=plot_filename,
3312 stamp_coordinate=stamp_coordinate,
3313 title=plot_title,
3314 vmin=vmin,
3315 vmax=vmax,
3316 hexbin=hexbin,
3317 )
3318 plot_index.append(plot_filename)
3320 # Add list of plots to plot metadata.
3321 complete_plot_index = _append_to_plot_index(plot_index)
3323 # Make a page to display the plots.
3324 _make_plot_html_page(complete_plot_index)
3326 return cubes
3329def _plot_and_save_postage_stamp_power_spectrum_series(
3330 cubes: iris.cube.Cube,
3331 coords: list[iris.coords.Coord],
3332 stamp_coordinate: str,
3333 filename: str,
3334 title: str,
3335 series_coordinate: str | None = None,
3336 **kwargs,
3337):
3338 """Plot and save postage (ensemble members) stamps for a power spectrum series.
3340 Parameters
3341 ----------
3342 cubes: Cube or CubeList
3343 Cube or Cubelist of the power spectrum data.
3344 coords: list[Coord]
3345 Coordinates to plot on the x-axis, one per cube.
3346 stamp_coordinate: str
3347 Coordinate that becomes different plots.
3348 filename: str
3349 Filename of the plot to write.
3350 title: str
3351 Plot title.
3352 series_coordinate: str, optional
3353 Coordinate being plotted on x-axis. In case of spectra frequency, physical_wavenumber, or wavelength.
3355 """
3356 # Use the smallest square grid that will fit the members.
3357 grid_size = math.ceil(math.sqrt(len(cubes.coord(stamp_coordinate).points)))
3359 fig = plt.figure(figsize=(10, 10), facecolor="w", edgecolor="k")
3360 model_colors_map = get_model_colors_map(cubes)
3361 # ax = plt.gca()
3362 # Make a subplot for each member.
3363 for member, subplot in zip(
3364 cubes.slices_over(stamp_coordinate), range(1, grid_size**2 + 1), strict=False
3365 ):
3366 ax = plt.subplot(grid_size, grid_size, subplot)
3368 # Store min/max ranges.
3369 y_levels = []
3371 line_marker = None
3372 line_width = 1
3374 for cube in iter_maybe(member):
3375 xcoord = _select_series_coord(cube, series_coordinate)
3376 xname = xcoord.points
3378 yfield = cube.data # power spectrum
3379 label = None
3380 color = "black"
3381 if model_colors_map: 3381 ↛ 3382line 3381 didn't jump to line 3382 because the condition on line 3381 was never true
3382 label = cube.attributes.get("model_name")
3383 color = model_colors_map.get(label)
3385 if member.coord(stamp_coordinate).points == [0]:
3386 ax.plot(
3387 xname,
3388 yfield,
3389 color=color,
3390 marker=line_marker,
3391 ls="-",
3392 lw=line_width,
3393 label=f"{label} (control)"
3394 if len(cube.coord(stamp_coordinate).points) > 1
3395 else label,
3396 )
3397 # Label with member if part of an ensemble and not the control.
3398 else:
3399 ax.plot(
3400 xname,
3401 yfield,
3402 color=color,
3403 ls="-",
3404 lw=1.5,
3405 alpha=0.75,
3406 label=f"{label} (member)",
3407 )
3409 # Calculate the global min/max if multiple cubes are given.
3410 _, levels, _ = colorbar_map_levels(cube, axis="y")
3411 if levels is not None: 3411 ↛ 3412line 3411 didn't jump to line 3412 because the condition on line 3411 was never true
3412 y_levels.append(min(levels))
3413 y_levels.append(max(levels))
3415 # Add some labels and tweak the style.
3416 title = f"{title}"
3417 ax.set_title(title, fontsize=16)
3419 # Set appropriate x-axis label based on coordinate
3420 if series_coordinate == "wavelength" or ( 3420 ↛ 3423line 3420 didn't jump to line 3423 because the condition on line 3420 was never true
3421 hasattr(xcoord, "long_name") and xcoord.long_name == "wavelength"
3422 ):
3423 ax.set_xlabel("Wavelength (km)", fontsize=14)
3424 elif series_coordinate == "physical_wavenumber" or ( 3424 ↛ 3429line 3424 didn't jump to line 3429 because the condition on line 3424 was always true
3425 hasattr(xcoord, "long_name") and xcoord.long_name == "physical_wavenumber"
3426 ):
3427 ax.set_xlabel("Wavenumber (km⁻¹)", fontsize=14)
3428 else: # frequency or check units
3429 if hasattr(xcoord, "units") and str(xcoord.units) == "km-1":
3430 ax.set_xlabel("Wavenumber (km⁻¹)", fontsize=14)
3431 else:
3432 ax.set_xlabel("Wavenumber", fontsize=14)
3434 ax.set_ylabel("Power Spectral Density", fontsize=14)
3435 ax.tick_params(axis="both", labelsize=12)
3437 # Set log-log scale
3438 ax.set_xscale("log")
3439 ax.set_yscale("log")
3441 # Add gridlines
3442 ax.grid(linestyle="--", color="grey", linewidth=1)
3443 # Ientify unique labels for legend
3444 handles = list(
3445 {
3446 label: handle
3447 for (handle, label) in zip(*ax.get_legend_handles_labels(), strict=True)
3448 }.values()
3449 )
3450 ax.legend(handles=handles, loc="best", ncol=1, frameon=True, fontsize=16)
3452 ax = plt.gca()
3453 ax.set_title(f"Member #{member.coord(stamp_coordinate).points[0]}")
3455 # Save plot.
3456 _save_close_figure(fig, "histogram postage stamp", filename)
3459def _plot_and_save_postage_stamps_in_single_plot_power_spectrum_series(
3460 cubes: iris.cube.Cube,
3461 coords: list[iris.coords.Coord],
3462 stamp_coordinate: str,
3463 filename: str,
3464 title: str,
3465 series_coordinate: str | None = None,
3466 **kwargs,
3467):
3468 """Plot and save power spectra for ensemble members in single plot.
3470 Parameters
3471 ----------
3472 cubes: Cube or CubeList
3473 Cube or Cubelist of the power spectrum data.
3474 coords: list[Coord]
3475 Coordinates to plot on the x-axis, one per cube.
3476 stamp_coordinate: str
3477 Coordinate that becomes different plots.
3478 filename: str
3479 Filename of the plot to write.
3480 title: str
3481 Plot title.
3482 series_coordinate: str, optional
3483 Coordinate being plotted on x-axis. In case of spectra frequency, physical_wavenumber, or wavelength.
3485 """
3486 fig, ax = plt.subplots(figsize=(10, 10), facecolor="w", edgecolor="k")
3487 model_colors_map = get_model_colors_map(cubes)
3489 line_marker = None
3490 line_width = 1
3492 # Compute ensemble statistics to show spread
3493 mean_cube = cubes.collapsed(stamp_coordinate, iris.analysis.MEAN)
3494 min_cube = cubes.collapsed(stamp_coordinate, iris.analysis.MIN)
3495 max_cube = cubes.collapsed(stamp_coordinate, iris.analysis.MAX)
3497 xcoord_global = mean_cube.coord(series_coordinate)
3498 x_global = xcoord_global.points
3500 for i, member in enumerate(cubes.slices_over(stamp_coordinate)):
3501 xcoord = _select_series_coord(member, series_coordinate)
3502 xname = xcoord.points
3504 yfield = member.data # power spectrum
3505 color = "black"
3506 if model_colors_map: 3506 ↛ 3510line 3506 didn't jump to line 3510 because the condition on line 3506 was always true
3507 label = member.attributes.get("model_name") if i == 0 else None
3508 color = model_colors_map.get(label)
3510 if member.coord(stamp_coordinate).points == [0]:
3511 ax.plot(
3512 xname,
3513 yfield,
3514 color=color,
3515 marker=line_marker,
3516 ls="-",
3517 lw=line_width,
3518 label=f"{label} (control)"
3519 if len(member.coord(stamp_coordinate).points) > 1
3520 else label,
3521 )
3522 # Label with member number if part of an ensemble and not the control.
3523 else:
3524 ax.plot(
3525 xname,
3526 yfield,
3527 color=color,
3528 ls="-",
3529 lw=1.5,
3530 alpha=0.75,
3531 label=label,
3532 )
3534 # Set appropriate x-axis label based on coordinate
3535 if series_coordinate == "wavelength" or ( 3535 ↛ 3538line 3535 didn't jump to line 3538 because the condition on line 3535 was never true
3536 hasattr(xcoord, "long_name") and xcoord.long_name == "wavelength"
3537 ):
3538 ax.set_xlabel("Wavelength (km)", fontsize=14)
3539 elif series_coordinate == "physical_wavenumber" or ( 3539 ↛ 3544line 3539 didn't jump to line 3544 because the condition on line 3539 was always true
3540 hasattr(xcoord, "long_name") and xcoord.long_name == "physical_wavenumber"
3541 ):
3542 ax.set_xlabel("Wavenumber (km⁻¹)", fontsize=14)
3543 else: # frequency or check units
3544 if hasattr(xcoord, "units") and str(xcoord.units) == "km-1":
3545 ax.set_xlabel("Wavenumber (km⁻¹)", fontsize=14)
3546 else:
3547 ax.set_xlabel("Wavenumber", fontsize=14)
3549 # Add ensemble spread shading
3550 ax.fill_between(
3551 x_global,
3552 min_cube.data,
3553 max_cube.data,
3554 color="grey",
3555 alpha=0.3,
3556 label="Ensemble spread",
3557 )
3559 # Add ensemble mean line
3560 ax.plot(x_global, mean_cube.data, color="black", lw=1, label="Ensemble mean")
3562 ax.set_ylabel("Power Spectral Density", fontsize=14)
3563 ax.tick_params(axis="both", labelsize=12)
3565 # Set y limits to global min and max, autoscale if colorbar doesn't exist.
3566 # Set log-log scale
3567 ax.set_xscale("log")
3568 ax.set_yscale("log")
3570 # Add gridlines
3571 ax.grid(linestyle="--", color="grey", linewidth=1)
3572 # Identify unique labels for legend
3573 handles = list(
3574 {
3575 label: handle
3576 for (handle, label) in zip(*ax.get_legend_handles_labels(), strict=True)
3577 }.values()
3578 )
3579 ax.legend(handles=handles, loc="best", ncol=1, frameon=True, fontsize=16)
3581 # Figure title.
3582 ax.set_title(title, fontsize=16)
3584 # Save plot.
3585 _save_close_figure(fig, "power spectra postage stamp", filename)