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:
Converts
xinto a one-dimensional, finitefloat64vector with_as_float_vector("x", x).Validates
statanddecimals; the acceptedstatvalues are"count","probability", and"density".Resolves the style name with
_resolve_style(style)and enters_style_context(...)to apply it and make behaviour consistent across notebooks.If
xlimorylimare provided, it validates them as pairs of finite values.If
ax is None, it creates a new figure withplt.subplots(...); otherwise it reuses the figure associated with the provided axis.Builds
hist_range_tupleifhist_rangeis provided, and checks that it satisfiesxmin < xmax.If
bin_widthis provided, it checks that it is positive, requiresbinsto be left at its default"auto", and explicitly builds the bin edges as integer multiples ofbin_width.Prepares the plotting options for the selected branch, adding
bar_colorandedgecoloronly when explicitly provided.For
"count", callsax.hist(...); for normalized modes, computes counts and edges with NumPy and draws the heights usingax.bar(...).If requested, it uses
bin_edgesto set x-axis ticks and labels, then applies any requested rotation.Computes the arithmetic mean and standard deviation of the sample.
If enabled, it adds the mean line and the \(\pm 1\sigma\) band.
Sets labels, title, grid, legend and axis limits.
Leaves
_style_context: the temporary style is removed and, in IPython/Jupyter, the new figures are displayed explicitly and closed.If
save_pathis 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.
xis not passed directly to Matplotlib: it is first normalized intovalues, which must be a one-dimensional, non-empty numeric array without non-finite values.statis validated before the figure is created; values other than the three supported strings raise an informativeValueError.decimalsis 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.mplstylefile;_style_context(...)therefore receivesNone, a path, or the name of a Matplotlib style. WithNoneit uses the currentrcParams; otherwise it passes the value toplt.style.context(...).xlimandylimare checked before any drawing happens. If they are present, they must be valid pairs of finite numbers.figsizeanddpiare passed toplt.subplots(...)only when they are explicitly provided. If the user passesax, the function does not create a new figure and reusesax.get_figure().constrained_layout=Trueis part of the standard behaviour whenhistogramcreates 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_rangeis given, it is validated with the same helper used for axis limits, plus an extra check:xmin < xmaxmust hold strictly.If
hist_rangeis not given,xminandxmaxare taken directly from the validated data invalues.bin_widthdoes not just change the bin width: it changes the construction strategy itself, because the edges are generated explicitly as integer multiplesk * bin_width.The indices
firstandlastusefloorandceil, aligning bins to integer multiples ofbin_widththat cover the selected interval. Building the edges from integer indices, rather than withnp.arangeon floating-point values, avoids extra edges beyondlast * 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 withax.hist(..., density=False).In normalized branches,
N = counts.sum()counts only observations included in the bins; whenN > 0, heights becomecounts / Nand, for"density", are also divided by the individual widths. WhenN == 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,histandbaruse the next color in the axes color cycle. The cycle is initialized fromaxes.prop_cyclewhen the axes are created and may advance with earlier calls;patch.facecolordoes not determine the bar color.edgecolor=Noneinstead leaves the edges to the active Matplotlib settings. Explicit values are forwarded to Matplotlib.The
bin_edgesreturned by Matplotlib ("count") or NumPy (normalized modes) are the source of ticks whenshow_bin_ticks=True.Bin-edge labels are formatted directly from the
bin_edgesused to draw the bars.decimalscontrols the text representation of the edges throughfmt = f".{decimals}f", and the same formatting is reused for the mean and the band.tick_rotationis independent ofshow_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
muis computed withnp.mean(values), whilesigmais delegated tostandard_deviationand therefore depends onddof.show_meanandshow_bandare independent: you can show only the line, only the band, both, or neither.mean_colorandband_coloroverride the style only when they are notNone; otherwise the function uses the colors of the active cycle.The mean legend entry uses
mean_symbol, while the band entry usesband_symbol.If
ylabelisNone, the function selects"Conteggi","Frequenza relativa", or"Densità di frequenza"according tostat; 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=Falsedisables major and minor grid lines; withshow_grid=True, it is enabled usingaxes.grid.axisandaxes.grid.whichfrom the current style, even ifaxes.grid=False; an explicitgrid_alphainstead selects theyaxis and sets the opacity.Saving happens at the end, after leaving
_style_context, withbbox_inches="tight": thesavefig.*settings of the temporary style are no longer active.dpiis passed tosavefig(...)only if the user explicitly requested it.The file format follows the extension of
save_path; if the path has no extension,.pdfis appended.
Important interactions between parameters
Some parameter combinations define the most important practical behaviour of the function.
bin_widthandbinsare mutually exclusive, except for the default case wherebinsis"auto"; a number, another rule or an array of edges together withbin_widthraiseValueError.With explicit bin edges, the edges determine which observations are included:
hist_rangedoes not apply an additional filter.hist_rangehas two different roles: ifbin_widthis absent, it is passed toax.hist(..., range=...); ifbin_widthis given, it is used to determine thexminandxmaxfrom which the bin edges are built.style=Noneuses the currentrcParams;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, andgrid_alphaoverride the style only when they are notNone.show_bin_ticks=Trueuses the same edges as the plot, returned by Matplotlib or NumPy depending on the mode.ddofonly affects the computation ofsigmaand therefore the \(\pm 1\sigma\) band; it does not change the histogram counts.statchanges only bar heights and the automatic y-axis label; the mean and standard deviation are still calculated from the full sample.figsizeonly has an effect whenax is None;dpican instead affect both figure creation and saving, but always only when it is explicitly provided.show_grid=Truealways enables the grid: the style selects its axes, ticks and appearance. With an explicitgrid_alpha, the function enables a horizontal grid on theyaxis with the requested opacity.save_pathalways saves the final figure, even whenaxwas passed in from outside and the figure was not created insidehistogram.In notebooks,
_style_contextshows only the new figures created inside the block and then closes them, to avoid double automatic display. This happens before saving withsave_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_rangedefines the numeric range from whichxminandxmaxare derivedbin_width=0.5forces explicit construction of the bin edges and therefore rules out abinsvalue other than"auto"style="mespy"explicitly requests the package style for that single callthe 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