diagnostic.visualizations#

Functions

create_custom_cmap(hex_color1, hex_color2, ...)

Create a custom colormap that transitions between two given hex colors and generates a specified number of colors.

plot_annual_cycle(da, **kwargs)

Plot the annual cycle of the data.

plot_diurnal_cycle(da, **kwargs)

Plot the daily cycle of the data.

plot_map(da, **kwargs)

Plots a simple map of a 2D xarray DataArray.

plot_maps_mod_ref_diff(da_mod, da_ref, da_diff)

Plots side-by-side comparison maps for model data, reference data, and their difference.

plot_metric_ranking(df_metric[, ax, ...])

Plots a heatmap of the ranking of metrics for different model members.

plot_points_on_map(d_point_coords[, ax, region])

Plot geographic points on a map using Cartopy, with optional region highlighting.

plot_time_series(da, **kwargs)

Plot a time series of the data.

plot_time_series_mod_ref(da_mod, da_ref[, ...])

Plot time series for both model and reference datasets on the same axes.

visualize_perkins_skill_score(da_mod, da_obs)

Visualize the Perkins Skill Score (PSS) by plotting the normalized histograms of the model and reference data, and display the PSS score and bin width used.

_add_features(ax, region=None)[source]#

Adds geographical features to a given cartopy GeoAxes.

Parameters: ax (cartopy.mpl.geoaxes.GeoAxesSubplot): The GeoAxes to which features are to be added.

Features Added: - Borders: Adds country borders with a dotted linestyle. - Coastlines: Adds coastlines with a specified linewidth and color. - extent: if region is given, cut out the plotting extent based on the lat and lon bounds given.

Notes: - The function can be extended to set the extent of the plot by uncommenting and modifying the

set_extent line to include appropriate longitude and latitude bounds.

Example: >>> fig, ax = plt.subplots(subplot_kw={‘projection’: ccrs.PlateCarree()}) >>> add_features(ax) >>> plt.show()

_get_gca(**kwargs)[source]#

Get the current axes as the axis passed in the keyword arguments or the current axis.

create_custom_cmap(hex_color1: str, hex_color2: str, num_colors: int)[source]#

Create a custom colormap that transitions between two given hex colors and generates a specified number of colors.

Parameters:
  • hex_color1 (str) – The starting color of the colormap in hex format (e.g., ‘#FF0000’ for red).

  • hex_color2 (str) – The ending color of the colormap in hex format (e.g., ‘#0000FF’ for blue).

  • num_colors (int) – The number of colors to generate in the colormap, including both the start and end colors.

Returns:

  • cmap (matplotlib.colors.LinearSegmentedColormap) – A colormap that can be used in plotting functions to visualize data with a color gradient from hex_color1 to hex_color2.

  • colors (numpy.ndarray) – An array of the RGB values for each of the colors in the generated colormap.

Example

>>> cmap, colors = create_custom_cmap("#FF0000", "#0000FF", 10)
>>> plt.imshow([colors], aspect='auto')
>>> plt.show()
plot_annual_cycle(da: DataArray, **kwargs)[source]#

Plot the annual cycle of the data.

Parameters:
  • da (xr.DataArray) – The data array to plot the annual cycle of.

  • **kwargs (dict) – Additional keyword arguments to pass to the xarray DataArray plot method.

Returns:

ax – The axes with the plotted annual cycle.

Return type:

matplotlib.axes.Axes

plot_diurnal_cycle(da: DataArray, **kwargs)[source]#

Plot the daily cycle of the data.

Parameters:
  • da (xr.DataArray) – The data array to plot the daily cycle of.

  • **kwargs (dict) – Additional keyword arguments to pass to the xarray DataArray plot method.

Returns:

ax – The axes with the plotted daily cycle.

Return type:

matplotlib.axes.Axes

plot_map(da: DataArray, **kwargs)[source]#

Plots a simple map of a 2D xarray DataArray.

Default plot settings:

  • subplot_kws: {‘projection’: ccrs.PlateCarree()}

  • cbar_kwargs: {‘label’: “{{da.attrs.get(‘long_name’, ‘Data’)}} ({{da.name}})”}

Parameters:#

daxr.DataArray

The 2D xarray DataArray to plot. It should have latitude and longitude dimensions.

titlestr, optional

The title for the plot. If not provided, a default title based on the DataArray’s long_name attribute will be set.

**kwargs :

Additional keyword arguments to pass to the xarray DataArray plot method.

Returns:#

axmatplotlib.axes.Axes

The matplotlib Axes with the plot.

plot_maps_mod_ref_diff(da_mod: DataArray, da_ref: DataArray, da_diff: DataArray, region=None, **kwargs)[source]#

Plots side-by-side comparison maps for model data, reference data, and their difference.

Parameters:
  • da_mod (xarray.DataArray) – The model data to be plotted. Expected to be a 2D array with latitude and longitude dimensions.

  • da_ref (xarray.DataArray) – The reference data to be plotted. Expected to be a 2D array with latitude and longitude dimensions.

  • da_diff (xarray.DataArray) – The difference between model and reference data (model - reference) to be plotted.

  • region (str, optional) – A string specifying the region for determining the plotting extent. Defaults to None.

  • **kwargs (dict, optional) –

    Additional keyword arguments for customizing the plots:

    • vmin (float): Minimum value for the color scale of the model and reference plots.

    • vmax (float): Maximum value for the color scale of the model and reference plots.

    • vmin_bias (float): Minimum value for the color scale of the bias plot.

    • vmax_bias (float): Maximum value for the color scale of the bias plot.

Returns:

A list containing the three axes objects for the model, reference, and bias plots.

Return type:

list of matplotlib.axes._subplots.AxesSubplot

Notes

  • All warnings are suppressed during the execution of this function.

  • Each subplot uses the PlateCarree projection and includes borders and coastlines.

  • The color scale for the model and reference plots is determined by the combined minimum and maximum values

across both datasets unless explicitly specified via vmin and vmax. - The bias plot uses a diverging color map (‘coolwarm’) centered around zero, with its range determined by the maximum absolute value of the difference unless overridden by vmin_bias and vmax_bias. - Titles for the subplots are positioned to the right and are derived from the ‘dataset’ attribute of the respective data arrays, if available. Otherwise, default titles (“Model”, “Reference”, “Model - Reference”) are used. - The figure title is set to the ‘long_name’ attribute of the reference data, followed by its variable name.

plot_metric_ranking(df_metric, ax=None, plot_colorbar=True, hex_color1=None, hex_color2=None, **kwargs)[source]#

Plots a heatmap of the ranking of metrics for different model members.

This function takes a DataFrame of metrics, calculates the rankings of these metrics for each model member, and creates a heatmap representing the ranks. The plot can optionally include a colorbar to represent the ranking levels. If no axis is provided, a new figure and axis are created for the plot.

Parameters:#

df_metricpd.DataFrame

A DataFrame containing the calculated metrics for different model members. Each column represents a model member, and each row represents a metric.

axmatplotlib.axes.Axes, optional

A pre-existing axis to plot the heatmap. If None (default), a new figure and axis are created.

plot_colorbarbool, optional

If True (default), a colorbar is added to the plot to represent the rank levels. If False, the heatmap is plotted without a colorbar.

hex_color1str

The starting color of the colormap in hex format (e.g., ‘#FF0000’ for red).

hex_color2str

The ending color of the colormap in hex format (e.g., ‘#0000FF’ for blue).

Returns:#

axmatplotlib.axes.Axes

The axis object containing the heatmap plot.

Notes:#

  • The color map has the ‘summer’ palette as default and is resampled to the number of model members.

  • A customized color map can be included or determined as an interpolation between two colorcodes (hex codes)

  • Rankings are normalized based on the number of model members.

  • The function supports colorbar ticks to represent custom rank labels, which are added only if plot_colorbar=True.

plot_points_on_map(d_point_coords: dict, ax=None, region=None)[source]#

Plot geographic points on a map using Cartopy, with optional region highlighting.

Parameters:
  • d_point_coords (dict) – A dictionary where keys are point identifiers (e.g., station names or IDs) and values are tuples of longitude and latitude coordinates (e.g., {‘Point1’: (lon1, lat1), ‘Point2’: (lon2, lat2)}).

  • ax (matplotlib.axes.Axes, optional) – The axes on which to plot the points. If None, a new figure and axes with a PlateCarree projection are created.

  • region (str or None, optional) – The region to highlight on the map. This could be a predefined region name (e.g., ‘belgium’) or None if no specific region is needed.

Returns:

The axes with the plotted points and the map features.

Return type:

matplotlib.axes.Axes

Example

>>> d_point_coords = {'Point1': (4.3517, 50.8503), 'Point2': (5.5413, 50.6326)}
>>> plot_points_on_map(d_point_coords, region="belgium")
plot_time_series(da: DataArray, **kwargs)[source]#

Plot a time series of the data.

Parameters:
  • da (xr.DataArray) – The data array to plot the time series of.

  • **kwargs (dict) – Additional keyword arguments to pass to the xarray DataArray plot method.

Returns:

ax – The axes with the plotted time series.

Return type:

matplotlib.axes.Axes

plot_time_series_mod_ref(da_mod: DataArray, da_ref: DataArray, ax=None, title: str = None, **kwargs)[source]#

Plot time series for both model and reference datasets on the same axes.

Parameters:
  • da_mod (xarray.DataArray) – The DataArray containing the model time series data.

  • da_ref (xarray.DataArray) – The DataArray containing the reference time series data.

  • ax (matplotlib.axes.Axes, optional) – The axes on which to plot the time series. If None, a new figure and axes are created.

  • title (str, optional) – The title for the plot. If None, a default title based on da_mod attributes is used.

  • **kwargs (dict) – Additional keyword arguments passed to xarray.DataArray.plot.

Returns:

The axes with the plotted time series.

Return type:

matplotlib.axes.Axes

visualize_perkins_skill_score(da_mod: DataArray, da_obs: DataArray, binwidth: float = None)[source]#

Visualize the Perkins Skill Score (PSS) by plotting the normalized histograms of the model and reference data, and display the PSS score and bin width used. For testing bin_widths

Parameters:
  • da_mod (xr.DataArray) – The model data to compare.

  • da_obs (xr.DataArray) – The reference data to compare against.

  • binwidth (float, optional) – The width of each bin for the histogram. If None, an optimal bin width should be calculated within the function (default is None).

Returns:

This function does not return any value. It displays a plot with the normalized histograms and Perkins Skill Score.

Return type:

None

Notes

The function calculates the Perkins Skill Score using the provided or default bin width, and plots the normalized histograms of the model and reference data. The plot also includes annotations for the Perkins Skill Score and bin width used.