On this page Signature

API Reference / mespy.histogram

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

x

required

Numeric sample: a list, a NumPy array or a pandas column. It must be one-dimensional, non-empty and contain only finite values.

stat

"count"

Bar height: counts \(n_i\), relative frequencies \(n_i/N\) or densities \(n_i/(N\,\Delta x_i)\).

ddof

0

Degrees of freedom subtracted when computing \(\sigma\): it divides by \(N - \mathrm{ddof}\). Use ddof=1 for the sample standard deviation.

Bins

Parameter

Default

Effect

bins

"auto"

Number of bins (10), a NumPy automatic rule ("auto", "fd", "sturges", "sqrt", …) or an explicit array of edges.

bin_width

None

Fixed bin width; the edges are aligned to integer multiples of bin_width. Alternative to bins.

hist_range

None

Pair (min, max) of the interval on which the bins are built. With None the range of the data is used.

Mean and band

Parameter

Default

Effect

show_mean

True

Draws the dashed line at the mean.

show_band

True

Draws the \(\bar{x} \pm \sigma\) band.

mean_symbol

r"\bar{x}"

LaTeX symbol of the mean in the legend, for example r"\bar{T}".

band_symbol

r"\pm \sigma"

LaTeX symbol of the band in the legend, for example r"\pm s".

decimals

3

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

label

"Dati"

Name of the bars in the legend.

xlabel

"Valore"

Label of the \(x\) axis: quantity and unit.

ylabel

None

Label of the \(y\) axis. With None it becomes "Conteggi", "Frequenza relativa" or "Densità di frequenza" depending on stat.

title

"Istogramma"

Plot title.

title_fontsize

style

Title font size.

title_pad

style

Distance in points between the title and the plot.

show_legend

True

Shows the legend.

legend_loc

style

Legend position, for example "upper left".

legend_fontsize

style

Legend font size.

Axes and grid

Parameter

Default

Effect

show_bin_ticks

True

Uses the bin edges as ticks on the \(x\) axis.

tick_rotation

0

Rotation in degrees of the \(x\) tick labels.

xlim

None

(min, max) limits of the \(x\) axis: they only change the visible region.

ylim

None

(min, max) limits of the \(y\) axis.

show_grid

True

With True, enables the grid on the axes and major/minor ticks selected by the style; with False, disables all grid lines.

grid_alpha

style

If given, draws the horizontal grid with this opacity.

Figure, style and saving

Parameter

Default

Effect

style

"mespy"

Style applied during the call only. None uses the current settings; it also accepts "report", "column" or the name of a Matplotlib style.

ax

None

Axes to draw on. With None a new figure is created.

figsize

style

Size (width, height) in inches; used only when the function creates the figure.

dpi

None

If explicit, sets the resolution of the new figure and saved file. With None, figure creation uses the style’s figure.dpi; saving uses savefig.dpi from the outer context.

save_path

None

Path of the file the figure is saved to; without an extension .pdf is added.

Colours and transparency

Parameter

Default

Effect

bar_color

axes color cycle

Bar fill color. With None, uses the next color in the axes color cycle, initialized from axes.prop_cycle when the axes are created; it does not use patch.facecolor.

edgecolor

style

Colour of the bar edges (white in the mespy style).

hist_alpha

0.85

Bar opacity, from 0 to 1.

mean_color

None

Colour of the mean line. With None it uses "C1", the second colour of the active style’s cycle.

band_color

None

Colour of the band. With None it uses "C2", the third colour of the active style’s cycle.

band_alpha

0.15

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, bins or hist_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_width builds the edges by itself. With \(a\) and \(b\) the extremes of the data (or of hist_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 why bin_width cannot be combined with bins, except for the default bins="auto". When all data equal a multiple of bin_width, no bars appear: use bins or widen hist_range.

  • hist_range acts differently depending on bins. 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. With bin_width it provides the extremes from which the edges are built.

  • xlim and ylim only 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 pass ax, the style applies only to the elements drawn by histogram: 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 with plt.style.use("mespy"), available after import mespy.

  • In notebooks the figure is shown immediately. In Jupyter, a figure created by histogram is shown and closed before the function returns: changes made afterwards, for example with ax.plot(...), do not appear automatically. If you want to add elements, create the axes first with plt.subplots() and pass them with ax=. In a script, on the other hand, call plt.show() to open the window.

  • Saving happens at the end. With save_path, the figure is saved with bbox_inches="tight" after the temporary style has been removed. Without an explicit dpi, Matplotlib uses savefig.dpi from the outer context: if it is "figure", it uses the figure resolution (100 dpi for a new figure with the mespy style); if it is numeric, it uses that value. For example, with savefig.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.