Histogram

This notebook shows a few typical uses of mp.histogram with the sample dataset included in the examples folder.

Imports

import matplotlib.pyplot as plt

import mespy as mp


df = mp.load_csv("data/test_misure.csv")
lunghezza = df["lunghezza_mm"]
sigma = df["sigma_mm"]

Basic histogram usage

The only essential argument is the numeric sample used to build the histogram. All other parameters are used to control the plot style, annotations, and layout.

fig, ax = mp.histogram(lunghezza)
../_images/f60a4b5ba2499ea350939aaea51d4d0d9ebd6a3c2be192a97ab6eba4ec0a41da.png

Custom labels and legend

You can change the data label, x axis, title, title size, and legend numeric precision without modifying the rest of the call.

mp.histogram(
    lunghezza,
    label="Lunghezze",
    xlabel="lunghezza [mm]",
    title="Distribuzione delle lunghezze",
    title_fontsize=11,
    decimals=2,
)
(<Figure size 2400x1500 with 1 Axes>,
 <Axes: title={'center': 'Distribuzione delle lunghezze'}, xlabel='lunghezza [mm]', ylabel='Conteggi'>)
../_images/97b0f5d01c4a80a3f3f5ea10543fdaf8b80dd5a5fdbcdc3e89869ef04a7c7b4c.png

Custom bin settings

bins and bin_width are alternatives: use the former to set the number or strategy of bins directly, and the latter to impose a constant width. hist_range restricts the range used to build the histogram.

fig, (ax_left, ax_right) = plt.subplots(
    1,
    2,
    figsize=(12, 4),
    dpi=140,
    constrained_layout=True,
)

mp.histogram(
    lunghezza,
    bins=6,
    xlabel="lunghezza [mm]",
    title="Numero fisso di bin",
    ax=ax_left,
)

mp.histogram(
    lunghezza,
    bin_width=0.025,
    hist_range=(25.15, 25.45),
    xlabel="lunghezza [mm]",
    title="bin_width con hist_range",
    ax=ax_right,
)

fig
../_images/773401a170b92b9a28a79bc03014facbab34577d0c333996edcbcff53d02eaa5.png ../_images/773401a170b92b9a28a79bc03014facbab34577d0c333996edcbcff53d02eaa5.png

Comparison across two axes

When you pass ax, mespy draws on the existing subplot and lets you combine multiple distributions in the same figure without changing the API.

fig, (ax_left, ax_right) = plt.subplots(
    1,
    2,
    figsize=(12, 4),
    dpi=140,
    constrained_layout=True,
)

mp.histogram(
    lunghezza,
    bins=8,
    xlabel="lunghezza [mm]",
    title="Distribuzione delle lunghezze",
    ax=ax_left,
)

mp.histogram(
    sigma,
    bins="sqrt",
    xlabel="sigma [mm]",
    title="Distribuzione delle incertezze",
    show_band=False,
    ax=ax_right,
)

fig
../_images/543bd4d89f8e71461e629a1df40245968e9314bf303f1357b5ed1f12d19a7d20.png ../_images/543bd4d89f8e71461e629a1df40245968e9314bf303f1357b5ed1f12d19a7d20.png

Related pages