Histogram
A complete guide to histogram, the MesPy function that turns a series of measurements into a histogram ready for a lab report. The page starts from the idea of a frequency distribution and puts the function to work on eleven examples that were actually executed: every plot you see is the real output of the code above it.
If you only need the parameter list, jump to API reference. If this is your first histogram, read the page from the top: each section builds on the concepts of the previous one.
This guide follows the current repository sources. The construction of edges with bin_width and grid control include changes made after version 2.0.0 was published on PyPI. To obtain the same results, install the sources as described in Development setup and run the examples from the same checkout.
The basics
From measurements to a distribution
When you repeat the same measurement several times, for example the period of a pendulum timed with a photogate, you do not always get the same number. Each measurement is an observation: a single value \(x_j\), with \(j = 1, \dots, N\). A list of fifty values, however, is hard to read at a glance: it does not immediately tell you where the measurements cluster, how spread out they are, or whether any of them is anomalous.
A histogram answers these questions. The value axis is split into consecutive intervals called bins, and you count how many observations fall into each one. The result is a frequency distribution: it no longer describes the individual measurements, but how often the values fall into each interval. Each bar has a bin as its base and, as its height, a quantity related to the number \(n_i\) of observations in bin \(i\).
Going from observations to frequencies has a cost and a benefit. The cost: inside a bin you can no longer tell one value from another, because the histogram only remembers how many there are. The benefit: the overall shape of the data becomes visible. In experimental physics this lets you:
see where the measurements cluster and how spread out they are around the central value;
recognise a symmetric, skewed or multi-peaked distribution;
spot anomalous values or gross errors before computing means and uncertainties;
compare the data with a theoretical model, such as a Gaussian or a Poisson distribution.
A histogram is always an estimate built from a finite sample. Two series of measurements of the same phenomenon produce different histograms, and the same sample changes appearance if you change the bins. The examples show this concretely.
What histogram does
histogram(x) takes a one-dimensional numeric sample and draws, in a single call:
the histogram bars, in one of three representations chosen with
stat: counts, relative frequencies or frequency densities;a dashed line at the arithmetic mean \(\bar{x}\) of the sample;
a transparent band \(\pm 1\) standard deviation wide around the mean;
a legend with the numerical values of the mean and the standard deviation, and the bin edges as ticks on the \(x\) axis.
The function applies the mespy plot style for the duration of the call only and returns the Matplotlib pair (fig, ax), so you can keep editing the plot with Matplotlib’s own tools.
It is just as important to know what histogram does not do. It does not return the bin counts, does not draw theoretical curves, does not run fits or statistical tests, and does not compute the uncertainty of the mean. When an example uses NumPy to check a result, the text says so.
Your first histogram
The bare minimum is an array of numbers. Here we simulate 40 measurements with a random number generator with a fixed seed (seed=1): running the code gives you exactly the same values, and therefore the same plot. Every other parameter keeps its default value.
import matplotlib.pyplot as plt
import numpy as np
from mespy import histogram
rng = np.random.default_rng(seed=1)
x = rng.normal(loc=10.0, scale=0.5, size=40)
fig, ax = histogram(x)
plt.show()
How to read the plot
Horizontal axis. It shows the measured values. The default label is
Valore(Italian for “value”): the function does not know the quantity or its unit, so you have to state them withxlabel.Bars. Each bar covers one bin. The ticks on the \(x\) axis are not “round” ticks: they are the bin edges themselves, written with three decimals (
decimals=3). The bin width, about \(0.27\), was chosen automatically bybins="auto".Vertical axis. With the default
stat="count"the height of a bar is the number \(n_i\) of measurements in the bin: for example, 12 measurements fall between \(9.986\) and \(10.254\). The labelConteggi(“counts”) is chosen automatically fromstat.Dashed line. It is the arithmetic mean of all 40 measurements, \(\bar{x} = 10.001\), also reported in the legend.
Green band. It extends from \(\bar{x} - \sigma\) to \(\bar{x} + \sigma\), with \(\sigma = 0.465\). With the default
ddof=0, \(\sigma\) is computed by dividing by \(N\), not by \(N-1\).Default texts. The title
Istogramma, the data labelDatiand the axis labelValoreare Italian placeholders: replace them in any plot you hand in.
What you cannot conclude
The data were generated from a Gaussian with mean \(10\) and standard deviation \(0.5\), but the histogram does not “prove” it: with 40 measurements the same figure would be compatible with many other symmetric distributions. The small difference between \(\sigma = 0.465\) and the true value \(0.5\) is also normal: it is a fluctuation due to the finite size of the sample.
Key takeaway
histogram(x) is enough to see the shape of your data, but the default texts are placeholders: a scientific plot always states the quantity and its unit on the \(x\) axis.
Guided examples
The examples follow a path: from reading a single histogram to choosing the bins, from the normalisations up to the typical problems of real data. Every code block is complete: you can copy it into a notebook or a script and run it as it is. The simulated data always use a fixed seed, so you get the same numbers and the same plots.
The strings inside the plots use symbols and code instead of words, so the same figure works for both the Italian and the English version of this page. The automatic \(y\) axis labels, such as Conteggi, remain in Italian because that is what histogram produces.
01Repeated measurements of a pendulum period
A simple pendulum about half a metre long oscillates with a period of about \(1.42\ \mathrm{s}\). Suppose you time it 50 times with a photogate: small random variations of the apparatus make every measurement slightly different. We simulate this experiment with Gaussian measurements with mean \(1.420\ \mathrm{s}\) and standard deviation \(0.010\ \mathrm{s}\).
Compared with the first example, we name the quantity and its unit, choose consistent symbols for the legend and use ddof=1. With ddof=1 the band shows the sample standard deviation \(s\), which divides by \(N-1\): it is the estimate normally used when the mean is computed from the same data. For consistency the band is called \(\pm s\).
import matplotlib.pyplot as plt
import numpy as np
from mespy import histogram
rng = np.random.default_rng(seed=42)
T = rng.normal(loc=1.420, scale=0.010, size=50)
fig, ax = histogram(
T,
ddof=1,
label=r"$T_i$",
xlabel=r"$T$ [s]",
title=r"$N = 50$",
mean_symbol=r"\bar{T}",
band_symbol=r"\pm s",
decimals=3,
)
plt.show()
inside = np.mean(np.abs(T - T.mean()) < T.std(ddof=1))
print(f"{inside:.0%}")
How to read the plot
The distribution is bell-shaped and nearly symmetric around the mean \(\bar{T} = 1.421\ \mathrm{s}\): the measurements gather in the central bins, with 13 values in the tallest one, and become rare moving away from the centre. The green band covers the interval \(\bar{T} \pm s\), with \(s = 0.008\ \mathrm{s}\).
The line printed below the plot, computed with NumPy and not by histogram, says that 64% of the measurements fall inside the band. For a Gaussian distribution you expect about 68%: with only 50 measurements, a difference of a few percentage points is perfectly normal.
What you cannot conclude
The band is not the uncertainty on the period. The standard deviation \(s\) describes how spread out a single measurement is; the uncertainty on the mean of \(N\) independent measurements is much smaller, \(s/\sqrt{N} \approx 0.008/\sqrt{50} \approx 0.001\ \mathrm{s}\), and histogram does not compute it. Moreover, the standard deviation only measures random effects: a systematic error, for example a photogate that triggers a few milliseconds late, shifts every measurement together and is invisible in the histogram.
Key takeaway
The \(\pm s\) band describes the spread of single measurements, not the uncertainty of the mean: the latter is \(s/\sqrt{N}\) and must be computed separately.
02How many bins?
Choosing the bins is the most important decision when you build a histogram, because it changes what the plot lets you see. Take 200 period measurements and draw them three times, changing only bins: 4 bins, the default automatic rule and 60 bins.
To compare the panels we create a figure with three axes and pass each of them to histogram with ax=. We activate the mespy style for the whole figure with plt.style.use("mespy"), remove the band and the legend to leave room for the bars, and turn off the ticks on the bin edges, which would overlap with 60 bins.
import matplotlib.pyplot as plt
import numpy as np
from mespy import histogram
plt.style.use("mespy")
rng = np.random.default_rng(seed=42)
T = rng.normal(loc=1.420, scale=0.010, size=200)
fig, axes = plt.subplots(1, 3, figsize=(12, 3.6))
for ax, bins in zip(axes, [4, "auto", 60], strict=True):
histogram(
T,
bins=bins,
ax=ax,
xlabel=r"$T$ [s]",
title=f"bins = {bins!r}",
show_bin_ticks=False,
show_band=False,
show_legend=False,
)
plt.show()
print(len(np.histogram_bin_edges(T, bins="auto")) - 1)
How to read the plot
4 bins (left). The bins are too wide: each one gathers measurements that are very different from each other. The plot only says that the values are concentrated around \(1.42\ \mathrm{s}\); the bell shape is lost and the tallest bar is not even centred on the mean.
"auto"(centre). NumPy chose 13 bins, the number printed below the plot. The bell shape is clear and the irregularities between neighbouring bins are small compared with the bar heights.60 bins (right). The bins are so narrow that each one contains few measurements. The bar height jumps from one bin to the next and empty bins appear: this is statistical noise, not physical structure in the data.
The vertical axis changes too. With stat="count" the height depends on the bin width: a wide bin collects more measurements, so the maximum counts go from about 100 to about 10. To compare histograms with different bins you need the normalisations of the example Counts, relative frequencies and densities.
NumPy’s "auto" rule chooses the bin width from the number of data points and their spread, taking the better result between the Sturges and the Freedman–Diaconis rules. It is a good starting point, not an optimal choice for every experiment. You can also pass to bins the other names accepted by numpy.histogram_bin_edges, such as "fd", "sturges" or "sqrt".
What you cannot conclude
None of the three panels is “the true one”. Peaks or gaps that appear only with a particular choice of bins should not be read as physical properties until they survive different reasonable choices.
Key takeaway
Too few bins hide the shape, too many fill it with noise. Always try more than one choice before drawing conclusions.
03Bin width and bin edges
It is often more natural to choose the width of the bins rather than their number, for example a multiple of the instrument resolution or a round value. With bin_width the function builds the edges by itself, aligning them to integer multiples of the chosen width.
Here we use \(5\ \mathrm{ms}\) wide bins on the same 200 measurements. We keep the ticks on the edges (show_bin_ticks=True, the default) and rotate them by 45° with tick_rotation so that they do not overlap. After the plot we print the minimum and maximum of the data and the edges that were used: since the ticks coincide with the edges, ax.get_xticks() returns them.
import matplotlib.pyplot as plt
import numpy as np
from mespy import histogram
rng = np.random.default_rng(seed=42)
T = rng.normal(loc=1.420, scale=0.010, size=200)
fig, ax = histogram(
T,
bin_width=0.005,
label=r"$T_i$",
xlabel=r"$T$ [s]",
title="bin_width = 0.005",
tick_rotation=45,
show_band=False,
)
plt.show()
print(T.min(), T.max())
print(ax.get_xticks())
How to read the plot
The data go from \(1.3987\) to \(1.4491\ \mathrm{s}\). The function rounded the first edge down and the last edge up to the nearest multiple of \(0.005\): the edges go from \(1.395\) to \(1.450\), and every measurement is inside the 11 bins. The rotated ticks are exactly these edges, so you can read from the plot the interval covered by each bar.
With round edges the histogram is easier to describe in words: “47 measurements between \(1.415\) and \(1.420\ \mathrm{s}\)”. Each bin includes its left edge and excludes its right edge, except the last one, which includes both.
When you need full control, for example to use the same bins in several plots or to compute the counts with NumPy, pass the array of edges directly: bins=np.linspace(1.395, 1.445, 11) creates 10 bins \(0.005\) wide between \(1.395\) and \(1.445\). This is what the next examples do.
What you cannot conclude
A round width is not automatically a suitable width. If it is smaller than the instrument resolution, empty bins alternate with full ones; the example Real data with finite resolution shows what happens.
Key takeaway
bin_width gives round, easy-to-read edges; an explicit array of edges gives full control and can be reused in other computations.
04Counts, relative frequencies and densities
The stat parameter decides what the height of a bar represents. Let \(n_i\) be the number of observations in bin \(i\), \(\Delta x_i\) its width and \(N = \sum_i n_i\) the number of observations inside the bins:
|
Height \(h_i\) |
Unit |
Sum equal to 1 |
|---|---|---|---|
|
\(n_i\) |
none, it is a number of measurements |
none: \(\sum_i h_i = N\) |
|
\(n_i / N\) |
dimensionless |
\(\sum_i h_i = 1\) |
|
\(n_i / (N\,\Delta x_i)\) |
inverse of the unit of \(x\) |
\(\sum_i h_i\,\Delta x_i = 1\) |
In the density what matters is the area of the bars: \(h_i\,\Delta x_i = n_i/N\) is the fraction of measurements in bin \(i\). We draw the three representations with the same edges and write the formula of each one as the \(y\) axis label.
import matplotlib.pyplot as plt
import numpy as np
from mespy import histogram
plt.style.use("mespy")
rng = np.random.default_rng(seed=42)
T = rng.normal(loc=1.420, scale=0.010, size=200)
edges = np.linspace(1.395, 1.445, 11)
ylabels = {
"count": r"$n_i$",
"probability": r"$n_i \,/\, N$",
"density": r"$n_i \,/\, (N\,\Delta T_i)$ [s$^{-1}$]",
}
fig, axes = plt.subplots(1, 3, figsize=(12, 3.6))
for ax, (stat, ylabel) in zip(axes, ylabels.items(), strict=True):
histogram(
T,
stat,
bins=edges,
ax=ax,
xlabel=r"$T$ [s]",
ylabel=ylabel,
title=f"stat = {stat!r}",
show_bin_ticks=False,
show_band=False,
show_legend=False,
)
plt.show()
The shape of the three figures is identical: only the vertical scale changes. histogram does not return the bar heights, but we can recompute them with numpy.histogram using the same edges and check the properties in the table. This cell continues the previous one and uses its variables T and edges.
counts, _ = np.histogram(T, bins=edges)
widths = np.diff(edges)
N = counts.sum()
probability = counts / N
density = counts / (N * widths)
print(T.size, N)
print(probability.sum())
print((density * widths).sum())
print(density.max())
Output
200 199
1.0
1.0
47.23618090452362
How to read the plot
Left, counts. The tallest bar contains 47 measurements. It is the most direct representation, but it depends both on the number of measurements and on the bin width.
Centre, relative frequencies. The same bar is about \(0.24\): it holds 24% of the measurements inside the bins. The heights are pure numbers and, as the second printed line confirms, they sum to 1.
Right, densities. The tallest bar is about \(47\ \mathrm{s^{-1}}\): it is a density per unit of period and can exceed 1 without any problem. Multiplied by the width \(0.005\ \mathrm{s}\) it gives \(0.24\) again. The third printed line confirms that the total area is 1.
The first printed line contains an important detail: there are 200 measurements, but only 199 fall into the bins. The largest value, \(1.4491\ \mathrm{s}\), lies beyond the last edge, \(1.445\). The normalisations divide by \(N = 199\), while the mean line uses all 200 measurements.
What you cannot conclude
A density of \(47\ \mathrm{s^{-1}}\) is not a probability, and the histogram density does not coincide with the probability density of the distribution the data come from: it is an estimate of it, subject to statistical fluctuations and to the choice of bins.
Key takeaway
Use counts to describe the sample, relative frequencies to compare samples of different size, densities when the bins have different widths.
05Bins of different widths
A Geiger counter records random events, and the time \(t\) between one event and the next follows an exponential distribution: short intervals are the most frequent, long ones become rarer and rarer. We simulate 500 intervals with a mean time of \(40\ \mathrm{ms}\).
Since the tail of the distribution is long and contains few data, it is reasonable to use narrow bins where there are many data and wide bins in the tail. We choose edges whose width doubles: \(0, 20, 40, 80, 160, 320\ \mathrm{ms}\). We draw the same data as counts and as densities.
import matplotlib.pyplot as plt
import numpy as np
from mespy import histogram
plt.style.use("mespy")
rng = np.random.default_rng(seed=3)
t = rng.exponential(scale=40.0, size=500)
edges = [0, 20, 40, 80, 160, 320]
fig, axes = plt.subplots(1, 2, figsize=(11, 3.8))
for ax, stat, ylabel in [
(axes[0], "count", r"$n_i$"),
(axes[1], "density", r"$n_i \,/\, (N\,\Delta t_i)$ [ms$^{-1}$]"),
]:
histogram(
t,
stat,
bins=edges,
ax=ax,
xlabel=r"$t$ [ms]",
ylabel=ylabel,
title=f"stat = {stat!r}",
decimals=0,
show_band=False,
show_legend=False,
)
plt.show()
print(np.histogram(t, bins=edges)[0])
How to read the plot
On the left, as counts, the wide bins look as important as the narrow ones. The counts printed below the plot are 182, 115, 120, 75 and 8: the bin between 40 and \(80\ \mathrm{ms}\) contains more measurements than the one between 20 and \(40\ \mathrm{ms}\) only because it is twice as wide, and the bin between 80 and \(160\ \mathrm{ms}\) holds 75 because it is \(80\ \mathrm{ms}\) wide. Read this way, the histogram would suggest that the distribution stays almost constant between 20 and \(80\ \mathrm{ms}\), which is false.
On the right, as densities, each count is divided by the width of its bin. The heights decrease steadily from one bin to the next, as expected from an exponential: the density again describes how likely values are per unit of time, regardless of how you chose the bins. The last bin, between 160 and \(320\ \mathrm{ms}\), has a density so low that it is barely visible.
The mean line is at about \(40\ \mathrm{ms}\), close to the mean time used in the simulation. In a skewed distribution like this one the mean does not coincide with the most frequent value, which is close to zero.
What you cannot conclude
With bins of different widths, the height in counts or relative frequencies cannot be compared from one bin to another. Even as densities, the wide bins in the tail contain few measurements and their height has a large relative uncertainty.
Key takeaway
With bins of different widths always use stat="density": it is the area of the bars, not their height, that represents the fraction of measurements.
06Different distributions, same band
The \(\bar{x} \pm s\) band always looks the same, but its meaning depends on the shape of the distribution. We compare three samples of 2000 values:
a uniform distribution between \(-0.5\) and \(0.5\), like the rounding error of a digital instrument expressed in units of its resolution;
a standard Gaussian distribution, typical of random errors that are the sum of many small contributions;
an exponential distribution with mean 1, like the waiting times of the previous example.
We use stat="density" to compare the shapes and compute with NumPy the fraction of values that falls inside the band.
import matplotlib.pyplot as plt
import numpy as np
from mespy import histogram
plt.style.use("mespy")
rng = np.random.default_rng(seed=5)
samples = {
r"$\mathcal{U}(-0.5,\ 0.5)$": rng.uniform(-0.5, 0.5, size=2000),
r"$\mathcal{N}(0,\ 1)$": rng.normal(0.0, 1.0, size=2000),
r"$\mathrm{Exp}(1)$": rng.exponential(1.0, size=2000),
}
fig, axes = plt.subplots(1, 3, figsize=(12, 3.8))
for ax, (title, x) in zip(axes, samples.items(), strict=True):
histogram(
x,
"density",
bins=30,
ddof=1,
ax=ax,
label=r"$x_i$",
xlabel=r"$x$",
title=title,
band_symbol=r"\pm s",
decimals=2,
show_bin_ticks=False,
legend_fontsize=8,
)
plt.show()
for title, x in samples.items():
inside = np.mean(np.abs(x - x.mean()) < x.std(ddof=1))
print(f"{title:28} {inside:.1%}")
How to read the plot
Uniform. The bars form an irregular plateau around 1, the value of the theoretical density \(1/(b-a)\). The band covers about 58% of the values; for a uniform distribution the theoretical value is \(1/\sqrt{3} \approx 57.7\%\).
Gaussian. The band covers 68.2% of the values, in agreement with the theoretical 68.3%.
Exponential. The distribution is strongly skewed and the band covers 87% of the values; the theoretical value is \(1 - e^{-2} \approx 86.5\%\). The band also extends to the left of zero, where there are no data: waiting times cannot be negative.
What you cannot conclude
The rule “68% of the data fall within one standard deviation” holds for the Gaussian, not for every distribution. And since the mean and standard deviation only summarise location and spread, two samples with the same \(\bar{x}\) and \(s\) can have completely different shapes: this is why the histogram remains indispensable.
Key takeaway
The \(\pm s\) band has a precise probabilistic meaning only if you know the shape of the distribution. Always look at the histogram before interpreting it.
07How many measurements do you need?
A histogram built from few measurements can look very different from the distribution they come from. We draw three samples, of 20, 200 and 5000 values, from the same period Gaussian and plot them with the same edges. We use stat="density", so that the heights can be compared even though the number of measurements changes, and fix the same vertical range with ylim.
import matplotlib.pyplot as plt
import numpy as np
from mespy import histogram
plt.style.use("mespy")
rng = np.random.default_rng(seed=11)
edges = np.linspace(1.385, 1.455, 15)
fig, axes = plt.subplots(1, 3, figsize=(12, 3.6))
for ax, n in zip(axes, [20, 200, 5000], strict=True):
T = rng.normal(loc=1.420, scale=0.010, size=n)
histogram(
T,
"density",
bins=edges,
ax=ax,
xlabel=r"$T$ [s]",
title=f"N = {n}",
ylim=(0, 75),
show_bin_ticks=False,
show_band=False,
show_legend=False,
)
plt.show()
How to read the plot
With 20 measurements (left) the histogram is irregular: an isolated bin, a gap, two separate peaks. None of these details is a property of the pendulum: the distribution the data come from is the same in the three panels. With 200 measurements (centre) the bell shape appears, still with some irregularities. With 5000 measurements (right) the profile is smooth and the maximum approaches the theoretical value \(1/(\sigma\sqrt{2\pi}) \approx 40\ \mathrm{s^{-1}}\).
The reason is statistical. With a fixed total \(N\) of independent observations from the same distribution and fixed bins, counts follow a multinomial distribution. If \(p_i\) is the probability of falling in bin \(i\), the count standard deviation is \(\sqrt{N p_i(1-p_i)}\). When \(p_i\) is small, the Poisson approximation gives an estimate \(\sqrt{n_i}\) and a relative uncertainty of about \(1/\sqrt{n_i}\): about 70% with 2 counts and 3% with 900. This approximation does not hold in general for heavily populated bins; counts in different bins are also correlated because their sum is fixed.
What you cannot conclude
The shape of a histogram does not uniquely determine the distribution the data come from, especially with few data. With 20 measurements you cannot tell a Gaussian from a two-peaked distribution; even with many data, different distributions can produce very similar histograms.
Key takeaway
For bins with small probability, \(\sqrt{n_i}\) is an approximate estimate of the count standard deviation. With fixed \(N\), the general formula is \(\sqrt{N p_i(1-p_i)}\). With little data, interpret only the most prominent histogram features.
08Discrete data: detector counts
Not every quantity is continuous. If you count the events recorded by a detector in 10-second intervals, you get integers \(k = 0, 1, 2, \dots\), which for a stable source follow a Poisson distribution. We simulate 300 intervals with a mean of 3.2 events.
For integer data the choice of edges is delicate. We compare the automatic rule with edges placed halfway between one integer and the next, \(k \pm 0.5\), so that each bin contains a single possible value. We use stat="probability": the height of each bar is the fraction of intervals with that number of events.
import matplotlib.pyplot as plt
import numpy as np
from mespy import histogram
plt.style.use("mespy")
rng = np.random.default_rng(seed=7)
k = rng.poisson(lam=3.2, size=300)
fig, axes = plt.subplots(1, 2, figsize=(11, 3.8))
for ax, bins in [
(axes[0], "auto"),
(axes[1], np.arange(-0.5, k.max() + 1.5, 1.0)),
]:
histogram(
k,
"probability",
bins=bins,
ax=ax,
label=r"$k_i$",
xlabel=r"$k$",
mean_symbol=r"\bar{k}",
title="bins = 'auto'" if isinstance(bins, str) else "bins = k ± 0.5",
decimals=1,
show_band=False,
legend_fontsize=8,
)
plt.show()
print(np.unique(k, return_counts=True))
How to read the plot
Automatic rule (left).
histogramconverts the data to floating-point numbers and the"auto"rule chooses 16 bins about \(0.56\) wide, narrower than the distance between two integers. Some bins contain no integer and are always empty: the regular gaps are an artefact of the bins, not a property of the source. Moreover, the bars are not centred on the integers and their width has no meaning for counted data.Edges at \(k \pm 0.5\) (right). Each bar is centred on an integer and contains only that value. The ticks at \(-0.5, 0.5, 1.5, \dots\) show the edges. The shape is the one expected for a Poisson distribution with mean close to 3, and the heights match the frequencies printed below the plot: for example 63 intervals out of 300, that is 0.21, with \(k = 3\).
What you cannot conclude
The bar at \(k = 9\) is taller than the one at \(k = 8\), but they correspond to 2 and 1 intervals respectively: with such small counts the difference is pure statistical noise, not a property of the source.
Key takeaway
For integer data use edges halfway between integers, for example np.arange(-0.5, k.max() + 1.5, 1.0): each bar then represents a single possible value.
09Real data with finite resolution
The file test_misure.csv, included in the documentation, contains 20 measurements of the length of an object, in millimetres, taken with an instrument of resolution \(0.05\ \mathrm{mm}\). We load it with MesPy’s load_csv; to run the code, download the file and put it in a data folder next to your notebook or script.
The resolution has an important consequence: the possible values are not continuous, but multiples of \(0.05\ \mathrm{mm}\). The first printed line confirms it: there are only five distinct values, from \(25.20\) to \(25.40\ \mathrm{mm}\). We compare three choices of bins: the automatic rule, bin_width=0.05 and explicit edges halfway between two possible values.
import matplotlib.pyplot as plt
import numpy as np
from mespy import histogram, load_csv
plt.style.use("mespy")
data = load_csv("data/test_misure.csv")
L = data["lunghezza_mm"]
print(np.unique(L, return_counts=True))
options = {
"bins = 'auto'": {},
"bin_width = 0.05": {"bin_width": 0.05},
"bins = L ± 0.025": {"bins": np.arange(25.175, 25.45, 0.05)},
}
fig, axes = plt.subplots(1, 3, figsize=(13, 3.8))
for ax, (title, binning) in zip(axes, options.items(), strict=True):
histogram(
L,
ax=ax,
xlabel=r"$L$ [mm]",
title=title,
tick_rotation=45,
show_legend=False,
**binning,
)
plt.show()
How to read the plot
bins="auto"(left). The automatic rule chooses 6 bins about \(0.033\ \mathrm{mm}\) wide, narrower than the resolution. One of the bins, between \(25.267\) and \(25.300\), contains no possible value and stays empty. The gap in the middle of the distribution looks like a real phenomenon, but it is only an artefact of the bins.bin_width=0.05(centre). The edges are multiples of \(0.05\), so they coincide with the measured values. Computed in floating point, some edges are exactly the round values while others come out slightly larger: for example \(25.200000000000003\) instead of \(25.2\). The measurements of \(25.25\), \(25.30\) and \(25.35\ \mathrm{mm}\) end up in the bin that starts at their own value, those of \(25.20\) and \(25.40\ \mathrm{mm}\) in the bin to the left. The result is an empty bin between \(25.20\) and \(25.25\) and a last bar, the tallest, that adds up the 5 measurements of \(25.35\) and the 2 of \(25.40\ \mathrm{mm}\): neither feature exists in the data.Edges halfway (right). With
bins=np.arange(25.175, 25.45, 0.05)each bin is centred on a possible value: 3, 4, 6, 5 and 2 measurements, as in the first printed line. It is the only one of the three representations that is faithful to the data.
What you cannot conclude
With 20 measurements and only five distinct values, the histogram does not allow you to judge the shape of the distribution: it is compatible with a Gaussian, but also with many other distributions. Moreover, when the spread of the measurements is comparable with the resolution, as here, \(s\) describes not only the variability of the measured object but also the discretisation of the instrument.
Key takeaway
With quantised data choose bins as wide as the resolution, or a multiple of it, with edges halfway between two possible values: never edges that coincide with the measured values.
10An outlier: leaving it out of the plot does not leave it out of the statistics
During a series of 31 period measurements, once the stopwatch is stopped late and the lab notebook records the problem: the recorded measurement is \(1.520\ \mathrm{s}\), far from all the others. Let us look at three ways of plotting these data:
all the measurements, with no precautions;
all the measurements, restricting the bins to the plausible interval with
hist_range=(1.39, 1.45);the measurements without the outlier, which is the last element of the array, hence
T[:-1].
This time we keep the legend, because the numerical values of the mean and the band are the point of the example.
import matplotlib.pyplot as plt
import numpy as np
from mespy import histogram
plt.style.use("mespy")
rng = np.random.default_rng(seed=8)
T = np.append(rng.normal(loc=1.420, scale=0.010, size=30), 1.520)
common = dict(
label=r"$T_i$", xlabel=r"$T$ [s]", show_bin_ticks=False, legend_fontsize=8
)
fig, axes = plt.subplots(1, 3, figsize=(13, 3.9))
histogram(T, ax=axes[0], title="T", **common)
histogram(T, ax=axes[1], title="T, hist_range", hist_range=(1.39, 1.45), **common)
histogram(T[:-1], ax=axes[2], title="T[:-1]", hist_range=(1.39, 1.45), **common)
plt.show()
How to read the plot
All measurements (left). The outlier stretches the data range, so the automatic bins become wide and the main distribution is squeezed into a few bars on the left. The isolated measurement at \(1.52\ \mathrm{s}\) is clearly visible: this is exactly how a histogram helps you discover gross errors.
With
hist_range(centre). The bars look clean, because the outlier lies outside the interval and does not enter the bins. The legend, however, tells another story: the mean is still \(1.422\ \mathrm{s}\) and \(\sigma = 0.021\ \mathrm{s}\), and the green band is much wider than the plotted distribution. The mean and \(\sigma\) are computed on the whole sample, outlier included.Outlier removed (right). Without the anomalous measurement the mean drops to \(1.419\ \mathrm{s}\) and \(\sigma\) halves to \(0.010\ \mathrm{s}\): now the band and the bars tell the same story.
The same holds for xlim: restricting the \(x\) axis hides the outlier from view, but changes neither the bins nor the statistics.
What you cannot conclude
A value is not discarded because it is inconvenient or far from the others. Here the removal is justified by a problem documented during the measurement; without a known cause, discarding data biases the result and must at least be stated and justified in the report.
Key takeaway
hist_range and xlim change what you see, not what you compute. To exclude a value from the statistics, remove it from the sample, and only for a good reason.
11Appearance, composition and saving
In a report the plot must be readable even when printed and consistent with the other figures. Every aesthetic parameter of histogram acts only on the call in which you pass it. In this example we use explicit edges, texts with symbols and units, custom colours for the bars, the mean and the band, the legend in the upper left corner, a stronger grid and a figure size suited to a page.
Colours are written in any format accepted by Matplotlib: a name such as "black", a hexadecimal code such as "#2d4f7c" or a reference to the style’s colour cycle such as "C1".
import matplotlib.pyplot as plt
import numpy as np
from mespy import histogram
rng = np.random.default_rng(seed=42)
T = rng.normal(loc=1.420, scale=0.010, size=200)
fig, ax = histogram(
T,
bins=np.linspace(1.395, 1.445, 11),
ddof=1,
label=r"$T_i$",
xlabel=r"$T$ [s]",
ylabel=r"$n_i$",
title=r"$N = 200$",
mean_symbol=r"\bar{T}",
band_symbol=r"\pm s",
decimals=3,
bar_color="#8fb3de",
edgecolor="#2d4f7c",
hist_alpha=1.0,
mean_color="#c0392b",
band_color="#c0392b",
band_alpha=0.10,
tick_rotation=45,
legend_loc="upper left",
title_fontsize=12,
grid_alpha=0.5,
figsize=(7, 4.2),
)
plt.show()
How to read the plot
The bars have a dark edge and are fully opaque (hist_alpha=1.0), so they stay distinguishable even in a black-and-white print. The mean line and the band share the same colour, so the legend associates them visually. The edge labels are rotated by 45° and written with three decimals (decimals=3), which also controls the digits of \(\bar{T}\) and \(s\) in the legend. The horizontal grid has opacity \(0.5\) thanks to grid_alpha.
Composing several plots. You have seen the procedure in the previous examples: create the figure and the axes with plt.subplots(...), pass each axes to histogram with ax= and, if you want the mespy style for the axes you created too, activate it first with plt.style.use("mespy"). With ax the function ignores figsize and returns the figure the axes belong to.
Saving the figure. Add save_path to the call. The format follows the file extension; without an extension the figure is saved as PDF, a vector format suited to LaTeX. For a PNG specify the resolution:
histogram(T, xlabel=r"$T$ [s]", save_path="periodo.pdf")
histogram(T, xlabel=r"$T$ [s]", save_path="periodo.png", dpi=300)
The file is written to the current working directory; if the path contains folders, they must already exist. For figures meant for a LaTeX report, MesPy also bundles the "report" and "column" styles, which you can pass with style="report" or style="column".
Key takeaway
Customise the appearance in the call, compose several panels with ax= and save with save_path: as PDF for LaTeX, as PNG with an explicit dpi.
Common mistakes
Data with missing values. A column read from a CSV file can contain empty cells, which become nan. histogram does not silently ignore them: it raises an error. The same happens if you misspell stat. The following code shows the real messages.
import numpy as np
from mespy import histogram
attempts = [
{"x": [1.42, np.nan, 1.43]},
{"x": [1.42, 1.41, 1.43], "stat": "pdf"},
]
for kwargs in attempts:
try:
histogram(**kwargs)
except ValueError as error:
print(f"ValueError: {error}")
Output
ValueError: x must contain only finite values
ValueError: 'stat' must be 'count', 'probability' or 'density' | got 'pdf'
For missing values decide explicitly what to do: drop incomplete rows when reading with load_csv(..., missing="drop"), or filter the array with x[np.isfinite(x)]. In both cases write down how many measurements you excluded.
The other frequent mistakes concern interpretation more than code:
Using
binsandbin_widthtogether. The function raisesValueError: 'bins' and 'bin_width' are mutually exclusive. Use only one of them. Choose the number of bins or their width.Comparing counts of different samples. With different numbers of measurements the counts cannot be compared: use
stat="probability"orstat="density"with the same edges. See Counts, relative frequencies and densities.Reading counts with bins of different widths. Wide bins look more populated. Use
stat="density", as in Bins of different widths.Mistaking the density for a probability. A density bar can exceed 1; the fraction of measurements is its area, \(h_i\,\Delta x_i\).
Mistaking the band for the uncertainty. The band is \(\pm\sigma\) of the single measurements; the uncertainty of the mean is \(\sigma/\sqrt{N}\). Remember also that the default is
ddof=0.Believing that
hist_rangeorxlimexclude data from the statistics. The mean and \(\sigma\) always use the whole sample, as An outlier shows.Edges that coincide with discrete values. With integer or quantised data, put the edges halfway between two possible values. See Discrete data and Real data with finite resolution.
Trusting a single choice of bins. A structure that appears only with certain bins is not a property of the data. See How many bins?.
Changing the figure after the call in a notebook. The figure created by
histogramhas already been shown: create the axes first and pass them withax=, as in the multi-panel examples, for instance How many bins?.Keeping the default texts.
Istogramma,ValoreandDatiare placeholders: always state the quantity and its unit.