Overview

Purpose

Draw a histogram of an experimental sample, with options to highlight the mean, the +- 1 sigma band, the legend, the grid, and figure saving.

Parameters

  • x: data to histogram.

  • ddof: parameter passed to standard_deviation for the band.

  • style: None uses the current rcParams, "mespy" loads the package style, and any other string is passed to Matplotlib as a style name.

  • bins: number of bins, automatic algorithm, or array of edges.

  • bin_width: fixed bin width. It cannot be used together with bins other than "auto".

  • hist_range: (xmin, xmax) pair used as the histogram range.

  • label, xlabel, ylabel, title: text labels.

  • show_bin_ticks, tick_rotation, and decimals: control x-axis formatting. decimals must be an integer between 0 and 20.

  • show_mean, show_band, show_legend, show_grid: enable or disable plot elements.

  • xlim, ylim: explicit axis limits.

  • ax: existing matplotlib axis to reuse.

  • figsize, dpi, and save_path: parameters for creating and saving the figure. figsize and dpi are passed to figure creation only when explicitly provided.

  • title_fontsize, title_pad, legend_fontsize, and legend_loc: targeted overrides for the title and legend. If left as None, the function uses the active style.

  • bar_color and edgecolor: targeted overrides for bar colours. If left as None, the function uses the values supplied by the active style or rcParams.

  • mean_color, band_color, hist_alpha, band_alpha, grid_alpha, and mean_symbol: control the mean line, the +- 1 sigma band, transparency, and the legend symbol. grid_alpha=None leaves the grid to the active style.

Returns

A (fig, ax) tuple with the figure and axis on which the histogram was drawn.

Errors and exceptions

  • ValueError if x is empty, not one-dimensional, or contains non-finite values.

  • ValueError if xlim, ylim, or hist_range are not valid pairs of finite values.

  • ValueError if hist_range does not satisfy xmin < xmax.

  • ValueError if bin_width <= 0.

  • ValueError if bin_width and bins are used together incompatibly.

  • ValueError if decimals is not a valid integer between 0 and 20.

  • ValueError if figsize is not a positive pair when the figure is created internally.

Example

import numpy as np

from mespy import histogram

x = np.random.normal(loc=0.0, scale=1.0, size=100)

fig, ax = histogram(
    x,
    bins=10,
    style="mespy",
    xlabel="x",
    title="Distribuzione delle misure",
    show_band=True,
)

Notes

  • The style is applied through _style_context, the same helper also used by lin_fit.

  • If ax is None, the function creates a new figure with plt.subplots.

  • If you pass ax, the returned figure is ax.get_figure().

  • Validation of limits, figure size, and decimals goes through _validate_axis_limits, _validate_figsize, and _validate_decimals.

  • save_path always saves with bbox_inches="tight"; dpi is added to saving only when it is explicitly provided.