disdrodb.viz package#

Submodules#

disdrodb.viz.dn module#

Plotting utilities for the Double Moment Normalization (DN) approach.

disdrodb.viz.dn.plot_loss_function(loss_function, q=(0, 0.8), s=15, cmap='Spectral_r', marker='x', c='black', **kwargs)[source][source]#

Plot loss function.

disdrodb.viz.dn.plot_normalized_dsd_and_ngg_fits(ds_dsd_norm_stats, c, mu, i, j, x_norm, xlims, ylims, add_ng_fits=True, cmap='Spectral_r', norm=None, ax=None)[source][source]#

Plot normalized DSD and fitted NormalizedGeneralizedGammaPSD.

disdrodb.viz.metadata module#

disdrodb.viz.plots module#

DISDRODB Plotting Tools.

disdrodb.viz.plots.add_dm_nw_cs_boundaries(ax)[source][source]#

Add C/S boundary on Dm-Nw plots.

disdrodb.viz.plots.add_one_to_one_line(ax, color='black', linewidth=0.8, linestyle='--', **kwargs)[source][source]#

Add 1:1 line.

disdrodb.viz.plots.add_panel_label(*, ax, text, loc='upper left', prop=None, frameon=True, borderpad=0.3, pad=0.0, boxstyle='square', alpha=1, facecolor='white', edgecolor='black', linewidth=0.4, fontsize=7, zorder=3, **kwargs)[source][source]#

Add panel label within subplot.

disdrodb.viz.plots.cmap_with_alpha(cmap, alpha=0.5, n=256)[source][source]#

Return a copy of a colormap with constant alpha.

disdrodb.viz.plots.compute_dense_lines(da: DataArray, coord: str, x_bins: list, y_bins: list, normalization='max')[source][source]#

Compute a 2D density-of-lines histogram from an xarray.DataArray.

Parameters:
  • da (xarray.DataArray) – Input data array. One of its dimensions (named by coord) is taken as the horizontal coordinate. All other dimensions are collapsed into “series,” so that each combination of the remaining dimension values produces one 1D line along coord.

  • coord (str) – The name of the coordinate/dimension of the DataArray to bin over. da.coords[coord] must be a 1D numeric array (monotonic is recommended).

  • x_bins (array-like) – Bin edges to bin the coordinate/dimension with shape (nx+1,). Must be monotonically increasing. The number of x-bins will be nx = len(x_bins) - 1.

  • y_bins (array-like) – Bin edges for the DataArray values with shape (ny+1,). Must be monotonically increasing. The number of y-bins will be ny = len(y_bins) - 1.

  • normalization (bool, optional) – If ‘none’, returns the raw histogram. By default, the function normalize the histogram by its global maximum (‘max’). Log-normalization (‘log’) is also available.

Returns:

2D histogram of shape (ny, nx). Dimensions are ('y', 'x'), where:

  • x: the bin-center coordinate of x_bins (length nx)

  • y: the bin-center coordinate of y_bins (length ny)

Each element out.values[y_i, x_j] is the count (or normalized count) of how many “series-values” from da fell into the rectangular bin x_bins[j] x_value < x_bins[j+1] and y_bins[i] data_value < y_bins[i+1].

Return type:

xarray.DataArray

References

Moritz, D., Fisher, D. (2018). Visualizing a Million Time Series with the Density Line Chart https://doi.org/10.48550/arXiv.1808.06019

disdrodb.viz.plots.define_event_title_string(start_time, end_time)[source][source]#

Create title string based on start_time and end_time.

disdrodb.viz.plots.draw_box(ax, x_box, y_box, facecolor='none', edgecolor='black', linewidth=1)[source][source]#

Draw rectangle box.

disdrodb.viz.plots.draw_boxes(ax, boxes, fontsize, colors_dict=None, yoffset=0, yfactor=1, add_label=True)[source][source]#

Draw boxes with label on top.

disdrodb.viz.plots.ensure_numeric_dimension_coordinate(da, dim, new_dim='sample_index')[source][source]#

Ensure numeric dimension coordinate.

If dim is non-numeric / non-datetime, create a numeric coordinate, swap dimensions, and return updated da and dim.

disdrodb.viz.plots.get_cmap_alpha(vmin=0, vmax=1, color=(1, 1, 1))[source][source]#

Create a single color colormap with linear gradient in alpha values.

Default color is white.

disdrodb.viz.plots.get_dataset_dsd_variable_name(ds, variables=None)[source][source]#

Return N(D) or n(D) variable name present in the xarray.Dataset.

disdrodb.viz.plots.get_dsd_variable(xr_obj, variable=None, diameter_dim='diameter_bin_center')[source][source]#

Return N(D), n(d) DataArray.

If N(D) or n(d) not available, derive n(d) from n(D,V).

Parameters:
  • xr_obj (xr.Dataset or xr.DataArray) – Input xarray object.

  • variable (str, optional) –

    Variable name to extract from the xarray object. If xr_obj is a DataArray, will return the DataArray and its name directly’. If xr_obj is a Dataset, if None, will search for candidate variables in order: [‘drop_number_concentration’, ‘drop_counts’, ‘raw_drop_counts’,

    ’raw_particle_counts’, ‘raw_drop_concentration’].

Returns:

(DataArray, variable_name)

Return type:

tuple

disdrodb.viz.plots.get_precipitation_legend_style(name)[source][source]#

Return (colors_dict, labels_dict) for supported categorical variables.

Supported:
  • rain_type

  • precipitation_type

  • hydrometeor_type

disdrodb.viz.plots.max_blend_images(ds_rgb, dim)[source][source]#

Max blend a RGBA DataArray across a samples dimensions.

disdrodb.viz.plots.normalize_array(arr, method='max')[source][source]#

Normalize a NumPy array according to the chosen method.

Parameters:
  • arr (numpy.ndarray) – Input array.

  • method (str) –

    Normalization method. Options:

    • ’max’ : Divide by the maximum value.

    • ’minmax’: Scale to [0, 1] range.

    • ’zscore’: Standardize to mean 0, std 1.

    • ’log’ : Apply log10 transform (shifted if min <= 0).

    • ’none’ : No normalization (return original array).

Returns:

Normalized array.

Return type:

numpy.ndarray

disdrodb.viz.plots.plot_colorbar(mappable, *, ax, cbar_inset_axes, x_pad, y_pad, orientation='vertical', label_position='left', fancybox_lw=0.2, fancybox_alpha=0.6, fancy_box_edgecolor='none', add_fancybox=True, **cbar_kwargs)[source][source]#

Add colorbar as inset axes with fancybox.

disdrodb.viz.plots.plot_colored_line(ds, var, hue, x=None, ax=None, cmap='turbo', vmin=None, vmax=None, mask=None, linewidth=1, add_colorbar=True)[source][source]#

Plot a 1D variable as a line colored by another variable, preserving gaps at NaNs.

Parameters:
  • ds (xarray.Dataset) –

  • var (str) – Variable for y-axis.

  • hue (str) – Variable controlling line color.

  • x (str, optional) – X coordinate name. If None, inferred from var.

  • ax (matplotlib.axes.Axes, optional) – Axis to plot on.

  • cmap (str, default "turbo") – Colormap for hue.

  • vmin (float, optional) – Color limits.

  • vmax (float, optional) – Color limits.

  • mask (xarray.DataArray or array-like, optional) – Boolean mask. False values become NaN.

  • linewidth (float, default 2) – Line width.

  • add_colorbar (bool, default True) – Whether to add a colorbar.

Returns:

  • ax (matplotlib.axes.Axes)

  • lc (matplotlib.collections.LineCollection)

disdrodb.viz.plots.plot_confusion_matrix(cm, labels, cmap='Blues', norm=None, xlabel='', ylabel='', title='', add_colorbar=False)[source][source]#

Plot confusion matrix.

disdrodb.viz.plots.plot_contour(contour, ax=None, **kwargs)[source][source]#

Plot contour [X,Y].

disdrodb.viz.plots.plot_dsd(xr_obj, variable=None, cmap=None, norm=None, yscale='linear', ax=None, d_lim=None, alpha=None, alpha_color=(1, 1, 1), add_colorbar=True, add_ylabel=True, add_time_axis=True, velocity_method='theoretical_velocity', time_dim='time', **plot_kwargs)[source][source]#

Plot drop number concentration N(D) or drop counts n(D) timeseries.

Parameters:
  • xr_obj (xr.Dataset or xr.DataArray) – Input xarray object containing drop data.

  • variable (str, optional) – Variable name to plot. If None and xr_obj is a Dataset, will search for candidate variables in order: [‘drop_number_concentration’, ‘raw_particle_counts’, ‘drop_counts’]. If xr_obj is a DataArray, it will be plotted directly.

  • cmap (matplotlib colormap, optional) – Colormap to use for the plot.

  • norm (matplotlib normalization, optional) – Normalization for the colormap.

  • yscale (str, optional) – Scale for y-axis (‘linear’ or ‘log’). Default is ‘linear’.

  • ax (matplotlib axes, optional) – Axes to plot on.

  • velocity_method (str, optional) – If the dataset has a velocity_method dimension, select the method to use for plotting. The default is “theoretical_velocity”.

Return type:

matplotlib axes or plot object

disdrodb.viz.plots.plot_dsd_dense_lines(xr_obj, *, dsd_var=None, cat_var=None, category_order=None, category_colors=None, category_labels=None, n_samples=None, random_state=None, diameter_bin_edges=None, y_bins=None, coord='diameter_bin_center', x_bins=None, ax=None, figsize=(3.4, 3.0), dpi=300, title='DSD', xlabel='$D$ [mm]', ylabel='$N(D)$ [m$^{-3}$ mm$^{-1}$]', xlim=(0, 8), ylim=(1, 20000.0), yscale='log', add_legend=True, legend_title=None, legend_loc='upper right', legend_kwargs=None, dense_lines_normalization='max', rgba_scaling='sqrt', resample=True, default_color='tab:blue', default_label=None)[source][source]#

Plot dense lines for a DSD variable.

Modes#

  1. If cat_var is None:

  • all samples are plotted together

  • optional sampling is applied to the full dataset before resampling

  1. If cat_var is provided:

  • one layer is plotted per category

  • optional sampling is applied independently within each category before resampling

disdrodb.viz.plots.plot_dsd_lines(xr_obj, *, dsd_var=None, cat_var=None, color_var=None, category_order=None, category_colors=None, category_labels=None, n_samples=None, sample_with_replacement=False, stratify_bins=None, stratify_quantiles=None, stratify_order='increasing', random_state=None, diameter_bin_edges=None, coord='diameter_bin_center', ax=None, figsize=(3.4, 3.0), dpi=300, title='DSD', xlabel='$D$ [mm]', ylabel='$N(D)$ [m$^{-3}$ mm$^{-1}$]', xlim=(0, 8), ylim=(1, 20000.0), yscale='log', add_legend=True, legend_title=None, legend_loc='upper right', legend_kwargs=None, cmap='viridis', norm=None, add_colorbar=True, colorbar_label=None, colorbar_kwargs=None, resample=True, default_color='tab:blue', default_label=None, linewidth=0.15, alpha=0.03, cbar_inset_axes=(0.68, 0.74, 0.3, 0.08), x_pad=0.03, y_pad=0.17)[source][source]#

Plot many individual DSD profiles as very thin lines.

Coloring modes#

  1. Default mode: - all profiles use default_color

  2. Category mode (cat_var): - one line collection per category - optional sampling is applied independently within each category - a legend can be added

  3. Continuous color mode (color_var): - each profile is colored according to a per-sample variable - optional sampling is applied before plotting - a colorbar can be added

Notes

cat_var and color_var are mutually exclusive.

disdrodb.viz.plots.plot_dsd_quicklook(xr_obj, hours_per_slice=3, max_rows=6, aligned=True, verbose=False, variable=None, cbar_label=None, cmap=None, norm=None, d_dim='diameter_bin_center', d_lim=(0.3, 5.5), d_label='Diameter [mm]', cbar_as_legend=True, cbar_xpos=0.73, cbar_width=0.25, bottom_right_str=None, bottom_right_str_fontsize=8, secondary_var=None, secondary_ylim=None, secondary_yscale='linear', secondary_color='black', secondary_alpha=1, secondary_linewidth=1, secondary_linestyle='-', secondary_label=None, secondary_hlines=None, precipitation_type=None, precipitation_legend_fontsize=7, precipitation_legend_colors=None, precipitation_legend_labels=None, precipitation_legend_ncol=None, precipitation_legend_height=0.3, add_dm=True, add_sigma_m=True, sigma_label='$2\\sigma_m$', sigma_linewidth=0.5, dm_linewidth=0.5, dpi=300)[source][source]#

Display multi-rows quicklook of N(D).

disdrodb.viz.plots.plot_l1_dsd_quicklook(xr_obj, precipitation_type='precipitation_type', **kwargs)[source][source]#

Define L1 DSD default quicklook.

disdrodb.viz.plots.plot_l2_dsd_quicklook(xr_obj, precipitation_type='rain_type', secondary_var='R', secondary_label=None, secondary_ylim=None, secondary_hlines=None, secondary_yscale=None, secondary_linestyle=':', **kwargs)[source][source]#

Define L2 DSD default quicklook.

disdrodb.viz.plots.plot_mask_contour(mask, ax=None, **kwargs)[source][source]#

Plot mask contour.

disdrodb.viz.plots.plot_normalized_dsd_lines(ds, *, dsd_var='drop_number_concentration', Nc='Nw', Dc='Dm', cat_var=None, category_order=None, category_colors=None, category_labels=None, n_samples=None, random_state=None, coord='diameter_bin_center', ax=None, figsize=(3.4, 3.0), dpi=300, title='Normalized DSD', xlabel='$D/D_m$ [-]', ylabel='$N(D)/N_w$ [-]', xlim=(0, 3), ylim=(0.0001, 10), yscale='log', add_legend=True, legend_title=None, legend_loc='upper right', legend_kwargs=None, default_color='tab:blue', default_label=None, linewidth=0.15, alpha=0.03)[source][source]#

Plot many individual normalized DSD profiles as very thin lines.

Modes#

  1. If cat_var is None:

  • all samples are plotted together

  • optional sampling is applied to the full dataset before resampling

  1. If cat_var is provided:

  • one line collection is plotted per category

  • optional sampling is applied independently within each category before resampling

disdrodb.viz.plots.plot_raw_and_filtered_spectra(ds, cmap=None, norm=None, extend='max', add_theoretical_average_velocity=True, add_measured_average_velocity=True, figsize=(6.9, 3.2), dpi=300)[source][source]#

Plot raw and filtered drop spectrum.

disdrodb.viz.plots.plot_spectrum(xr_obj, variable='raw_drop_number', ax=None, cmap=None, norm=None, extend='max', add_colorbar=True, cbar_kwargs=None, title=None, plot_hc_rain_mask_boundary=False, d_lim=None, v_lim=None, **plot_kwargs)[source][source]#

Plot the spectrum.

Parameters:
  • xr_obj (xarray.Dataset or xarray.DataArray) – Input xarray object. If Dataset, the variable to plot must be specified. If DataArray, it must have both diameter and velocity dimensions.

  • variable (str) – Name of the variable to plot if xr_obj is a Dataset.

  • ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, uses current axes or creates a new one.

  • cmap (matplotlib.colors.Colormap, optional) – Colormap to use. If None, uses ‘Spectral_r’ with ‘under’ set to ‘none’.

  • norm (matplotlib.colors.Normalize, optional) – Normalization for colormap. If None, uses LogNorm with vmin=1.

  • extend (str, optional) – Whether to draw arrows on the colorbar to indicate out-of-range values. Valid options are ‘neither’, ‘min’, ‘max’, ‘both’. Default is ‘max’.

  • add_colorbar (bool, optional) – Whether to add a colorbar. Default is True.

  • cbar_kwargs (dict, optional) – Additional keyword arguments for colorbar. If None, uses {‘label’: ‘Number of particles ‘}.

  • title (str, optional) – Title of the plot. If not provided, defaults to the timestep or time range of the spectrum.

  • **plot_kwargs (dict) – Additional keyword arguments passed to xarray’s plot.pcolormesh method.

Notes

If the input DataArray has a time dimension, it is summed over time before plotting unless FacetGrid options (e.g., col, row) are specified in plot_kwargs.

If FacetGrid options are used, the plot will create a grid of subplots for each time slice.

To create a FacetGrid plot, use:

ds.isel(time=slice(0, 9)).disdrodb.plot_spectrum(col=”time”, col_wrap=3)

disdrodb.viz.plots.plot_spectrum_evolution(ds, legend_variables=None, legend_loc='lower right', legend_ncol=1, xlim=None, ylim=None, plot_hc_rain_mask_boundary=False, gif_filepath=None, frame_rate=6, **plot_kwargs)[source][source]#

Plot the evolution of disdrodb spectra over time.

Parameters:
  • ds (xarray.Dataset) – Dataset containing ‘time’ dimension and ‘disdrodb’.

  • legend_variables (list of str, optional) – Dataset variables to display in the legend.

  • legend_ncol (int, optional) – Number of legend entries per row (horizontal layout).

  • xlim (tuple, optional) – Axis limits passed to matplotlib.

  • ylim (tuple, optional) – Axis limits passed to matplotlib.

  • plot_kwargs (dict) – Additional keyword arguments passed to plot_spectrum().

disdrodb.viz.plots.plot_stations_spectra(list_datasets, *, norm, cmap=None, d_lim=(0, 8), v_lim=(0, 10), base_width=6.9, base_ncols=3, dpi=100, height_per_row=2.3, ncols=None, title_attr='station_name', add_grid=False, add_colorbar=True, cbar_subplot_idx=0, cbar_inset_axes=(0.5, 0.15, 0.4, 0.05), cbar_label='Counts', x_pad=0.02, y_pad=0.12, colorbar_orientation='horizontal', colorbar_label_position='top', cbar_kwargs=None, cbar_labelsize=6, grid_kwargs=None)[source][source]#

Plot disdrometer spectra of various stations a compact panel figure.

Parameters:
  • list_datasets (list) – List of stations.

  • cmap (str, optional) – If None, defaults to “Spectral_r”.

  • d_lim (tuple) – Diameter axis limits.

  • v_lim (tuple) – Fall velocity axis limits.

  • base_width (float) – Figure width in inches for base_ncols columns.

  • base_ncols (int) – Reference number of columns for base_width.

  • height_per_row (float) – Figure height per row in inches.

  • ncols (int, optional) – Number of columns. If None, uses min(len(list_datasets), base_ncols).

  • title_attr (str) – Dataset attribute used for subplot titles.

  • add_colorbar (bool) – Whether to add one inset colorbar.

disdrodb.viz.plots.to_rgba(obj, cmap='viridis', norm=None, scaling='none')[source][source]#

Map a xarray DataArray (or numpy array) to RGBA with optional alpha-scaling.

Module contents#

DISDRODB Visualization Module.