On this page Execution sequence

API Reference / mespy.histogram

Implementation

This page describes the internal flow of histogram and the order in which validation, bin selection, and plotting additions are applied. Unlike Overview, the goal here is not to repeat the parameter list, but to show how the function actually builds the histogram.

The following snippets are taken from the current src/mespy/plot_utils.py implementation. Private helpers are mentioned only to clarify the flow; complete details are documented in _as_float_vector, _validate_axis_limits, _validate_figsize, _validate_decimals, _style_context, and standard_deviation.

Execution sequence

The implementation follows this sequence:

  1. Converts x into a one-dimensional, finite float64 vector with _as_float_vector("x", x).

  2. Validates stat and decimals; the accepted stat values are "count", "probability", and "density".

  3. Resolves the style name with _resolve_style(style) and enters _style_context(...) to apply it and make behaviour consistent across notebooks.

  4. If xlim or ylim are provided, it validates them as pairs of finite values.

  5. If ax is None, it creates a new figure with plt.subplots(...); otherwise it reuses the figure associated with the provided axis.

  6. Builds hist_range_tuple if hist_range is provided, and checks that it satisfies xmin < xmax.

  7. If bin_width is provided, it checks that it is positive, requires bins to be left at its default "auto", and explicitly builds the bin edges as integer multiples of bin_width.

  8. Prepares the plotting options for the selected branch, adding bar_color and edgecolor only when explicitly provided.

  9. For "count", calls ax.hist(...); for normalized modes, computes counts and edges with NumPy and draws the heights using ax.bar(...).

  10. If requested, it uses bin_edges to set x-axis ticks and labels, then applies any requested rotation.

  11. Computes the arithmetic mean and standard deviation of the sample.

  12. If enabled, it adds the mean line and the \(\pm 1\sigma\) band.

  13. Sets labels, title, grid, legend and axis limits.

  14. Leaves _style_context: the temporary style is removed and, in IPython/Jupyter, the new figures are displayed explicitly and closed.

  15. If save_path is given, saves the figure, therefore outside the temporary style, and finally returns (fig, ax).

Input validation, style, and figure setup

values = _as_float_vector("x", x)

if not isinstance(stat, str) or stat not in ("count", "probability", "density"):
    raise ValueError(
        f"'stat' must be 'count', 'probability' or 'density' | got {stat!r}"
    )

decimals = _validate_decimals(decimals)

with _style_context(_resolve_style(style)):
    if xlim is not None:
        xlim = _validate_axis_limits(
            xlim,
            name="xlim",
            min_label="xmin",
            max_label="xmax",
        )

    if ylim is not None:
        ylim = _validate_axis_limits(
            ylim,
            name="ylim",
            min_label="ymin",
            max_label="ymax",
        )

    if ax is None:
        import matplotlib.pyplot as plt

        subplots_kwargs: dict = {"constrained_layout": True}
        if figsize is not None:
            subplots_kwargs["figsize"] = _validate_figsize(figsize)
        if dpi is not None:
            subplots_kwargs["dpi"] = dpi
        fig, ax = plt.subplots(**subplots_kwargs)
    else:
        fig = ax.get_figure()

This first block sets the function’s input contract.

  • x is not passed directly to Matplotlib: it is first normalized into values, which must be a one-dimensional, non-empty numeric array without non-finite values.

  • stat is validated before the figure is created; values other than the three supported strings raise an informative ValueError.

  • decimals is validated immediately and remains available both for x-axis ticks and for the textual labels of the mean and band.

  • _resolve_style(style) turns the short names of the styles bundled with the package, "mespy" included, into the path of the corresponding .mplstyle file; _style_context(...) therefore receives None, a path, or the name of a Matplotlib style. With None it uses the current rcParams; otherwise it passes the value to plt.style.context(...).

  • xlim and ylim are checked before any drawing happens. If they are present, they must be valid pairs of finite numbers.

  • figsize and dpi are passed to plt.subplots(...) only when they are explicitly provided. If the user passes ax, the function does not create a new figure and reuses ax.get_figure().

  • constrained_layout=True is part of the standard behaviour when histogram creates the figure on its own.

  • In IPython/Jupyter notebooks, the same context manager also handles explicit display of new figures to avoid awkward interactions with plt.style.context(...).

Range and bin construction

hist_range_tuple: tuple[float, float] | None = None
if hist_range is not None:
    hist_range_tuple = _validate_axis_limits(
        hist_range,
        name="hist_range",
        min_label="xmin",
        max_label="xmax",
    )
    xmin, xmax = hist_range_tuple
    if xmin >= xmax:
        raise ValueError("'hist_range' requires xmin < xmax")
else:
    xmin = float(np.min(values))
    xmax = float(np.max(values))

if bin_width is not None:
    if bin_width <= 0:
        raise ValueError("'bin_width' must be > 0.")

    if not (isinstance(bins, str) and bins == "auto"):
        raise ValueError(
            "'bins' and 'bin_width' are mutually exclusive. Use only one of them"
        )

    first = np.floor(xmin / bin_width)
    last = np.ceil(xmax / bin_width)
    bins = np.arange(first, last + 1) * bin_width

Here the function decides the numeric domain on which the histogram is built.

  • If hist_range is given, it is validated with the same helper used for axis limits, plus an extra check: xmin < xmax must hold strictly.

  • If hist_range is not given, xmin and xmax are taken directly from the validated data in values.

  • bin_width does not just change the bin width: it changes the construction strategy itself, because the edges are generated explicitly as integer multiples k * bin_width.

  • The indices first and last use floor and ceil, aligning bins to integer multiples of bin_width that cover the selected interval. Building the edges from integer indices, rather than with np.arange on floating-point values, avoids extra edges beyond last * bin_width. Observations in this possible range extension remain included in the denominator of normalized modes as well.

Counts, normalization, and x-axis formatting

if stat == "count":
    hist_kwargs: dict = {
        "bins": bins,
        "range": hist_range_tuple if bin_width is None else None,
        "density": False,
        "alpha": hist_alpha,
        "label": label,
    }
    if bar_color is not None:
        hist_kwargs["color"] = bar_color
    if edgecolor is not None:
        hist_kwargs["edgecolor"] = edgecolor

    _, bin_edges, _ = ax.hist(values, **hist_kwargs)
else:
    counts, bin_edges = np.histogram(
        values,
        bins=bins,
        range=hist_range_tuple if bin_width is None else None,
    )
    widths = np.diff(bin_edges)
    heights = counts.astype(float)
    included = counts.sum()
    if included > 0:
        heights /= included
        if stat == "density":
            heights /= widths

    bar_kwargs: dict = {"alpha": hist_alpha}
    if bar_color is not None:
        bar_kwargs["color"] = bar_color
    if edgecolor is not None:
        bar_kwargs["edgecolor"] = edgecolor
    bars = ax.bar(bin_edges[:-1], heights, width=widths, align="edge", **bar_kwargs)
    if bars:
        # Match ax.hist's legend order by labelling the first patch.
        bars[0].set_label(label)

fmt = f".{decimals}f"
if show_bin_ticks:
    ax.set_xticks(bin_edges)
    ax.set_xticklabels([f"{edge:{fmt}}" for edge in bin_edges])

if tick_rotation != 0:
    ax.tick_params(axis="x", rotation=tick_rotation)

This is where the plot is actually drawn.

  • The "count" branch draws the bars directly with ax.hist(..., density=False).

  • In normalized branches, N = counts.sum() counts only observations included in the bins; when N > 0, heights become counts / N and, for "density", are also divided by the individual widths. When N == 0, they remain zero.

  • ax.bar(..., align="edge", width=np.diff(bin_edges)) aligns each bar to its left edge and respects unequal widths. Matplotlib autoscales to the final heights, without double normalization.

  • With bar_color=None, hist and bar use the next color in the axes color cycle. The cycle is initialized from axes.prop_cycle when the axes are created and may advance with earlier calls; patch.facecolor does not determine the bar color. edgecolor=None instead leaves the edges to the active Matplotlib settings. Explicit values are forwarded to Matplotlib.

  • The bin_edges returned by Matplotlib ("count") or NumPy (normalized modes) are the source of ticks when show_bin_ticks=True.

  • Bin-edge labels are formatted directly from the bin_edges used to draw the bars.

  • decimals controls the text representation of the edges through fmt = f".{decimals}f", and the same formatting is reused for the mean and the band.

  • tick_rotation is independent of show_bin_ticks: if it is non-zero, the rotation is applied to the x axis in any case.

The "count" branch uses the line color cycle through hist; the "probability" and "density" branches use the bar color cycle through bar. Both derive from axes.prop_cycle, but they can advance independently if you reuse an axes for several plots.

Mean, band, and plot finalization

mu = float(np.mean(values))
sigma = standard_deviation(values, ddof=ddof)

if mean_color is None:
    mean_color = "C1"
if band_color is None:
    band_color = "C2"

if show_mean:
    ax.axvline(
        mu,
        color=mean_color,
        linestyle="--",
        linewidth=1.2,
        label=rf"${mean_symbol} = {mu:{fmt}}$",
    )

if show_band:
    ax.axvspan(
        mu - sigma,
        mu + sigma,
        color=band_color,
        alpha=band_alpha,
        label=rf"${band_symbol} = {sigma:{fmt}}$",
    )

ax.set_xlabel(xlabel)
default_ylabel = {
    "count": "Conteggi",
    "probability": "Frequenza relativa",
    "density": "Densità di frequenza",
}[stat]
ax.set_ylabel(ylabel if ylabel is not None else default_ylabel)

title_kwargs: dict = {}
if title_fontsize is not None:
    title_kwargs["fontsize"] = title_fontsize
if title_pad is not None:
    title_kwargs["pad"] = title_pad
ax.set_title(title, **title_kwargs)

from matplotlib import rcParams

if not show_grid:
    ax.grid(False, which="both")
else:
    grid_kwargs = {
        "axis": rcParams["axes.grid.axis"],
        "which": rcParams["axes.grid.which"],
    }
    if grid_alpha is not None:
        grid_kwargs.update(axis="y", alpha=grid_alpha)
    ax.grid(True, **grid_kwargs)

if show_legend:
    legend_kwargs: dict = {}
    if legend_fontsize is not None:
        legend_kwargs["fontsize"] = legend_fontsize
    if legend_loc is not None:
        legend_kwargs["loc"] = legend_loc
    ax.legend(**legend_kwargs)

if xlim is not None:
    ax.set_xlim(xlim)

if ylim is not None:
    ax.set_ylim(ylim)

# Fine del blocco `with _style_context(...)`: da qui lo stile temporaneo
# non è più attivo e, nei notebook, la figura è già stata mostrata.

if save_path is not None:
    save_path = Path(save_path)
    if save_path.suffix == "":
        save_path = save_path.with_suffix(".pdf")
    savefig_kwargs: dict = {"bbox_inches": "tight"}
    if dpi is not None:
        savefig_kwargs["dpi"] = dpi
    fig.savefig(save_path, **savefig_kwargs)

return fig, ax

The last part adds the statistical elements and completes the axis configuration.

  • The mean mu is computed with np.mean(values), while sigma is delegated to standard_deviation and therefore depends on ddof.

  • show_mean and show_band are independent: you can show only the line, only the band, both, or neither.

  • mean_color and band_color override the style only when they are not None; otherwise the function uses the colors of the active cycle.

  • The mean legend entry uses mean_symbol, while the band entry uses band_symbol.

  • If ylabel is None, the function selects "Conteggi", "Frequenza relativa", or "Densità di frequenza" according to stat; it always respects an explicit value.

  • Title and legend receive extra keyword arguments only when the user has provided them; in all other cases, the active style configuration remains in effect.

  • The grid has three branches: show_grid=False disables major and minor grid lines; with show_grid=True, it is enabled using axes.grid.axis and axes.grid.which from the current style, even if axes.grid=False; an explicit grid_alpha instead selects the y axis and sets the opacity.

  • Saving happens at the end, after leaving _style_context, with bbox_inches="tight": the savefig.* settings of the temporary style are no longer active. dpi is passed to savefig(...) only if the user explicitly requested it.

  • The file format follows the extension of save_path; if the path has no extension, .pdf is appended.

Important interactions between parameters

Some parameter combinations define the most important practical behaviour of the function.

  • bin_width and bins are mutually exclusive, except for the default case where bins is "auto"; a number, another rule or an array of edges together with bin_width raise ValueError.

  • With explicit bin edges, the edges determine which observations are included: hist_range does not apply an additional filter.

  • hist_range has two different roles: if bin_width is absent, it is passed to ax.hist(..., range=...); if bin_width is given, it is used to determine the xmin and xmax from which the bin edges are built.

  • style=None uses the current rcParams; style="mespy", style="report", and the other bundled styles are resolved by the package; any other string is passed straight through Matplotlib.

  • bar_color, mean_color, band_color, edgecolor, title_fontsize, title_pad, legend_fontsize, legend_loc, and grid_alpha override the style only when they are not None.

  • show_bin_ticks=True uses the same edges as the plot, returned by Matplotlib or NumPy depending on the mode.

  • ddof only affects the computation of sigma and therefore the \(\pm 1\sigma\) band; it does not change the histogram counts.

  • stat changes only bar heights and the automatic y-axis label; the mean and standard deviation are still calculated from the full sample.

  • figsize only has an effect when ax is None; dpi can instead affect both figure creation and saving, but always only when it is explicitly provided.

  • show_grid=True always enables the grid: the style selects its axes, ticks and appearance. With an explicit grid_alpha, the function enables a horizontal grid on the y axis with the requested opacity.

  • save_path always saves the final figure, even when ax was passed in from outside and the figure was not created inside histogram.

  • In notebooks, _style_context shows only the new figures created inside the block and then closes them, to avoid double automatic display. This happens before saving with save_path, which works on the figure already closed but still valid.

Commented example

from mespy import histogram

fig, ax = histogram(
    x,
    bin_width=0.5,
    hist_range=(-2, 3),
    style="mespy",
    show_mean=True,
    show_band=True,
    decimals=2,
)

In this example:

  • hist_range defines the numeric range from which xmin and xmax are derived

  • bin_width=0.5 forces explicit construction of the bin edges and therefore rules out a bins value other than "auto"

  • style="mespy" explicitly requests the package style for that single call

  • the mean line and the \(\pm 1\sigma\) band are added after the histogram is drawn

  • if x-axis ticks are enabled, they are shown using the bin edges formatted with 2 decimal places