histogram
These pages describe the current repository sources. The construction of edges with bin_width and grid control differ from the 2.0.0 distribution already published on PyPI. To reproduce the behavior described here, follow Development setup.
Signature
histogram(
x: ArrayLike,
stat: Literal["count", "probability", "density"] = "count",
*,
ddof: int | float = 0,
style: str | None = "mespy",
bins: int | str | ArrayLike = "auto",
bin_width: float | None = None,
hist_range: ArrayLike | None = None,
label: str = "Dati",
xlabel: str = "Valore",
ylabel: str | None = None,
title: str = "Istogramma",
show_bin_ticks: bool = True,
tick_rotation: int | float = 0,
decimals: int = 3,
show_mean: bool = True,
show_band: bool = True,
show_legend: bool = True,
show_grid: bool = True,
xlim: ArrayLike | None = None,
ylim: ArrayLike | None = None,
ax: Axes | None = None,
figsize: ArrayLike | None = None,
dpi: int | None = None,
save_path: str | None = None,
title_fontsize: int | float | None = None,
title_pad: int | float | None = None,
legend_fontsize: int | float | None = None,
legend_loc: str | None = None,
bar_color: str | None = None,
mean_color: str | None = None,
band_color: str | None = None,
edgecolor: str | None = None,
hist_alpha: float = 0.85,
band_alpha: float = 0.15,
grid_alpha: float | None = None,
mean_symbol: str = r"\bar{x}",
band_symbol: str = r"\pm \sigma",
) -> tuple[Figure, Axes]
histogram draws a histogram of a numeric sample and can add the mean, a \(\pm 1\sigma\) band, legend, grid, and figure saving. stat selects counts ("count", default), relative frequencies ("probability"), or frequency densities ("density"). It can be passed as the second positional argument or by keyword. By default it applies the mespy Matplotlib style; pass style=None to use the current rcParams, or another style name to delegate to Matplotlib.
The figsize, dpi, title_fontsize, title_pad, legend_fontsize, legend_loc, bar_color, mean_color, band_color, edgecolor, and grid_alpha parameters can inherit from the active style when left as None. The hist_alpha, band_alpha, mean_symbol, and band_symbol parameters remain explicit per-call overrides instead.
Parameters by purpose
The 37 parameters are grouped by what they control. Defaults marked as “style” are read from the Matplotlib style that is active during the call, which is mespy by default.
Data and representation
Parameter |
Default |
Effect |
|---|---|---|
|
required |
Numeric sample: a list, a NumPy array or a pandas column. It must be one-dimensional, non-empty and contain only finite values. |
|
|
Bar height: counts \(n_i\), relative frequencies \(n_i/N\) or densities \(n_i/(N\,\Delta x_i)\). |
|
|
Degrees of freedom subtracted when computing \(\sigma\): it divides by \(N - \mathrm{ddof}\). Use |
Bins
Parameter |
Default |
Effect |
|---|---|---|
|
|
Number of bins ( |
|
|
Fixed bin width; the edges are aligned to integer multiples of |
|
|
Pair |
Mean and band
Parameter |
Default |
Effect |
|---|---|---|
|
|
Draws the dashed line at the mean. |
|
|
Draws the \(\bar{x} \pm \sigma\) band. |
|
|
LaTeX symbol of the mean in the legend, for example |
|
|
LaTeX symbol of the band in the legend, for example |
|
|
Decimal digits of the mean and \(\sigma\) in the legend and of the edges on the \(x\) axis; an integer from 0 to 20. |
Text and legend
Parameter |
Default |
Effect |
|---|---|---|
|
|
Name of the bars in the legend. |
|
|
Label of the \(x\) axis: quantity and unit. |
|
|
Label of the \(y\) axis. With |
|
|
Plot title. |
|
style |
Title font size. |
|
style |
Distance in points between the title and the plot. |
|
|
Shows the legend. |
|
style |
Legend position, for example |
|
style |
Legend font size. |
Axes and grid
Parameter |
Default |
Effect |
|---|---|---|
|
|
Uses the bin edges as ticks on the \(x\) axis. |
|
|
Rotation in degrees of the \(x\) tick labels. |
|
|
|
|
|
|
|
|
With |
|
style |
If given, draws the horizontal grid with this opacity. |
Figure, style and saving
Parameter |
Default |
Effect |
|---|---|---|
|
|
Style applied during the call only. |
|
|
Axes to draw on. With |
|
style |
Size |
|
|
If explicit, sets the resolution of the new figure and saved file. With |
|
|
Path of the file the figure is saved to; without an extension |
Colours and transparency
Parameter |
Default |
Effect |
|---|---|---|
|
axes color cycle |
Bar fill color. With |
|
style |
Colour of the bar edges (white in the |
|
|
Bar opacity, from 0 to 1. |
|
|
Colour of the mean line. With |
|
|
Colour of the band. With |
|
|
Band opacity, from 0 to 1. |
Behaviours worth knowing
Some behaviours cannot be read from the signature but change how you should read the plot.
The mean and \(\sigma\) always use the whole sample. They do not depend on
stat,binsorhist_range: even the measurements left out of the bins contribute to the line and the band. With \(N\) values,\[\bar{x} = \frac{1}{N}\sum_{j=1}^{N} x_j, \qquad \sigma = \sqrt{\frac{1}{N - \mathrm{ddof}}\sum_{j=1}^{N}\left(x_j - \bar{x}\right)^2}.\]Bins are half-open intervals. Each bin is \([a, b)\): it includes its left edge and excludes its right edge. Only the last one is closed, \([a, b]\). A value that lies exactly on an edge goes into the bin on the right, and tiny rounding errors on the edge can move it into the bin on the left.
The normalisations only count the observations inside the bins. In
"probability"and"density", \(N = \sum_i n_i\) is the number of observations actually inside the bins, which can be smaller than the sample size. If no observation falls into the bins, every height stays zero.bin_widthbuilds the edges by itself. With \(a\) and \(b\) the extremes of the data (or ofhist_range) and \(w\) the width, the edges are the integer multiples \(k\,w\) from \(\lfloor a/w \rfloor\, w\) to \(\lceil b/w \rceil\, w\). This is whybin_widthcannot be combined withbins, except for the defaultbins="auto". When all data equal a multiple ofbin_width, no bars appear: usebinsor widenhist_range.hist_rangeacts differently depending onbins. With a number of bins or an automatic rule, it bounds the interval and values outside it do not enter the bars. With an explicit array of edges it is ignored, because the edges are in charge. Withbin_widthit provides the extremes from which the edges are built.xlimandylimonly change the view. They do not modify bins, counts or normalisations.The style is temporary. With
style="mespy"the style holds only during the call and does not change the global settings. If you passax, the style applies only to the elements drawn byhistogram: the axes and the figure keep the properties they had when they were created. For multi-panel plots it is convenient to activate the style for the whole session withplt.style.use("mespy"), available afterimport mespy.In notebooks the figure is shown immediately. In Jupyter, a figure created by
histogramis shown and closed before the function returns: changes made afterwards, for example withax.plot(...), do not appear automatically. If you want to add elements, create the axes first withplt.subplots()and pass them withax=. In a script, on the other hand, callplt.show()to open the window.Saving happens at the end. With
save_path, the figure is saved withbbox_inches="tight"after the temporary style has been removed. Without an explicitdpi, Matplotlib usessavefig.dpifrom the outer context: if it is"figure", it uses the figure resolution (100 dpi for a new figure with themespystyle); if it is numeric, it uses that value. For example, withsavefig.dpi=233, a 100 dpi figure is saved as a 233 dpi PNG. To select the file resolution directly, pass, for example,dpi=300.
For a step-by-step guide, with eleven executed examples and the statistical meaning of every option, see Histogram in the Examples section.
Overview summarizes parameters, normalizations, errors and a usage example; Implementation walks through the internal flow step by step.