On this page Purpose

API Reference / mespy.histogram

Overview

Purpose

Draw a histogram of an experimental sample, with options to highlight the mean, the \(\pm 1\sigma\) band, the legend, the grid, and figure saving.

Parameters

  • x: data to histogram.

  • stat: "count" (default), "probability", or "density"; second positional argument or keyword argument.

  • ddof: parameter passed to standard_deviation for the band.

  • style: None uses the current rcParams; the names of the styles bundled with the package are resolved automatically; 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. With ylabel=None, the mode selects "Conteggi", "Frequenza relativa", or "Densità di frequenza"; an explicit value is respected.

  • 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: explicit bar color. With None, uses the next color in the axes color cycle, initialized from axes.prop_cycle, not patch.facecolor. edgecolor: explicit edge color; with None, the active Matplotlib settings apply.

  • mean_color, band_color, hist_alpha, band_alpha, grid_alpha, mean_symbol, band_symbol: control the mean line, the \(\pm 1\sigma\) band, transparency, and the legend symbols. mean_color=None, band_color=None, and grid_alpha=None leave the choice to the active style.

Normalization and physical interpretation

Let \(n_i\) be the count in bin \(i\), \(N=\sum_i n_i\) the number of observations actually included, and \(\Delta x_i\) the bin width:

stat

Height \(h_i\)

Interpretation

"count"

\(n_i\)

Number of observations in the interval.

"probability"

\(n_i/N\)

Dimensionless relative frequency; \(\sum_i h_i=1\).

"density"

\(n_i/(N\Delta x_i)\)

Density with inverse units of x; \(\sum_i h_i\Delta x_i=1\).

The formulas also apply to unequal-width bins. In density mode, the area of each bar represents the relative frequency in the interval; its height may exceed 1.

If no observations fall in the bins, all bars have zero height: normalization is not applied and no division by zero is performed. Empty input x still raises ValueError.

The mean and standard deviation always use the full sample, independently of stat and any observations excluded by the bins. ddof continues to affect only the standard deviation.

Returns

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

Errors and exceptions

  • ValueError if stat is not one of the three supported modes.

  • 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,
)

With the same bin edges, you can compare the normalized modes:

edges = [-3, -1, 0, 0.5, 2, 3]
histogram(x, "probability", bins=edges)
histogram(x, stat="density", bins=edges)

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. The format follows the path extension; without an extension, .pdf is used.