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 tostandard_deviationfor the band.style:Noneuses the currentrcParams; 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 withbinsother than"auto".hist_range:(xmin, xmax)pair used as the histogram range.label,xlabel,ylabel,title: text labels. Withylabel=None, the mode selects"Conteggi","Frequenza relativa", or"Densità di frequenza"; an explicit value is respected.show_bin_ticks,tick_rotation, anddecimals: control x-axis formatting.decimalsmust 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, andsave_path: parameters for creating and saving the figure.figsizeanddpiare passed to figure creation only when explicitly provided.title_fontsize,title_pad,legend_fontsize, andlegend_loc: targeted overrides for the title and legend. If left asNone, the function uses the active style.bar_color: explicit bar color. WithNone, uses the next color in the axes color cycle, initialized fromaxes.prop_cycle, notpatch.facecolor.edgecolor: explicit edge color; withNone, 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, andgrid_alpha=Noneleave 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:
|
Height \(h_i\) |
Interpretation |
|---|---|---|
|
\(n_i\) |
Number of observations in the interval. |
|
\(n_i/N\) |
Dimensionless relative frequency; \(\sum_i h_i=1\). |
|
\(n_i/(N\Delta x_i)\) |
Density with inverse units of |
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
ValueErrorifstatis not one of the three supported modes.ValueErrorifxis empty, not one-dimensional, or contains non-finite values.ValueErrorifxlim,ylim, orhist_rangeare not valid pairs of finite values.ValueErrorifhist_rangedoes not satisfyxmin < xmax.ValueErrorifbin_width <= 0.ValueErrorifbin_widthandbinsare used together incompatibly.ValueErrorifdecimalsis not a valid integer between 0 and 20.ValueErroriffigsizeis 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 bylin_fit.If
axisNone, the function creates a new figure withplt.subplots.If you pass
ax, the returned figure isax.get_figure().Validation of limits, figure size, and
decimalsgoes through_validate_axis_limits,_validate_figsize, and_validate_decimals.save_pathalways saves withbbox_inches="tight";dpiis added to saving only when it is explicitly provided. The format follows the path extension; without an extension,.pdfis used.