Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 3e98181

Browse filesBrowse files
committed
DOC: normalizing histograms
1 parent d8e272f commit 3e98181
Copy full SHA for 3e98181

File tree

Expand file treeCollapse file tree

3 files changed

+215
-62
lines changed
Filter options
Expand file treeCollapse file tree

3 files changed

+215
-62
lines changed

‎galleries/examples/statistics/hist.py

Copy file name to clipboardExpand all lines: galleries/examples/statistics/hist.py
+2-2Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@
3636
axs[0].hist(dist1, bins=n_bins)
3737
axs[1].hist(dist2, bins=n_bins)
3838

39+
plt.show()
40+
3941

4042
# %%
4143
# Updating histogram colors
@@ -99,8 +101,6 @@
99101
# We can also define custom numbers of bins for each axis
100102
axs[2].hist2d(dist1, dist2, bins=(80, 10), norm=colors.LogNorm())
101103

102-
plt.show()
103-
104104
# %%
105105
#
106106
# .. admonition:: References

‎galleries/examples/statistics/histogram_features.py

Copy file name to clipboardExpand all lines: galleries/examples/statistics/histogram_features.py
-60Lines changed: 0 additions & 60 deletions
This file was deleted.
+213Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
"""
2+
.. redirect-from:: /gallery/statistics/histogram_features
3+
4+
===================================
5+
Histogram bins, density, and weight
6+
===================================
7+
8+
The `.Axes.hist` method can flexibly create histograms in a few different ways,
9+
which is flexible and helpful, but can also lead to confusion. In particular,
10+
you can:
11+
12+
- bin the data as you want, either with an automatically chosen number of
13+
bins, or with fixed bin edges,
14+
- normalize the histogram so that its integral is one,
15+
- and assign weights to the data points, so that each data point affects the
16+
count in its bin differently.
17+
18+
The Matplotlib ``hist`` method calls `numpy.histogram` and plots the results,
19+
therefore users should consult the numpy documentation for a definitive guide.
20+
21+
Histograms are created by defining bin edges, and taking a dataset of values
22+
and sorting them into the bins, and counting or summing how much data is in
23+
each bin. In this simple example, 9 numbers between 1 and 4 are sorted into 3
24+
bins:
25+
"""
26+
27+
import matplotlib.pyplot as plt
28+
import numpy as np
29+
30+
rng = np.random.default_rng(19680801)
31+
32+
xdata = np.array([1.2, 2.3, 3.3, 3.1, 1.7, 3.4, 2.1, 1.25, 1.3])
33+
xbins = np.array([1, 2, 3, 4])
34+
35+
# changing the style of the histogram bars just to make it
36+
# very clear where the boundaries of the bins are:
37+
style = {'facecolor': 'none', 'edgecolor': 'C0', 'linewidth': 3}
38+
39+
fig, ax = plt.subplots()
40+
ax.hist(xdata, bins=xbins, **style)
41+
42+
# plot the xdata locations on the x axis:
43+
ax.plot(xdata, 0*xdata, 'd')
44+
ax.set_ylabel('Number per bin')
45+
ax.set_xlabel('x bins (dx=1.0)')
46+
47+
# %%
48+
# Modifying bins
49+
# ==============
50+
#
51+
# Changing the bin size changes the shape of this sparse histogram, so its a
52+
# good idea to choose bins with some care with respect to your data. Here we
53+
# make the bins half as wide.
54+
55+
xbins = np.arange(1, 4.5, 0.5)
56+
57+
fig, ax = plt.subplots()
58+
ax.hist(xdata, bins=xbins, **style)
59+
ax.plot(xdata, 0*xdata, 'd')
60+
ax.set_ylabel('Number per bin')
61+
ax.set_xlabel('x bins (dx=0.5)')
62+
63+
# %%
64+
# We can also let numpy (via Matplotlib) choose the bins automatically, or
65+
# specify a number of bins to choose automatically:
66+
67+
fig, ax = plt.subplot_mosaic([['auto', 'n4']],
68+
sharex=True, sharey=True, layout='constrained')
69+
70+
ax['auto'].hist(xdata, **style)
71+
ax['auto'].plot(xdata, 0*xdata, 'd')
72+
ax['auto'].set_ylabel('Number per bin')
73+
ax['auto'].set_xlabel('x bins (auto)')
74+
75+
ax['n4'].hist(xdata, bins=4, **style)
76+
ax['n4'].plot(xdata, 0*xdata, 'd')
77+
ax['n4'].set_xlabel('x bins ("bins=4")')
78+
79+
# %%
80+
# Normalizing histograms: density and weight
81+
# ==========================================
82+
#
83+
# Counts-per-bin is the default length of each bar in the histogram. However,
84+
# we can also normalize the bar lengths as a probability density function using
85+
# the ``density`` parameter:
86+
87+
fig, ax = plt.subplots()
88+
ax.hist(xdata, bins=xbins, density=True, **style)
89+
90+
91+
# %%
92+
# This normalization can be a little hard to interpret when just exploring the
93+
# data. The value attached to each bar is divided by the total number of data
94+
# points _and_ the width of the bin, and the values _integrate_ to one when
95+
# integrating across the full range of data.
96+
#
97+
# The usefulness of this normalization is a little more clear when we draw from
98+
# a known distribution and try to compare with theory. So, choose 1000 points
99+
# from a normal distribution, and also calculate the known probability density
100+
# function
101+
102+
xdata = rng.normal(size=1000)
103+
xpdf = np.arange(-4, 4, 0.1)
104+
pdf = 1 / (np.sqrt(2 * np.pi)) * np.exp(-xpdf**2 / 2)
105+
106+
# %%
107+
# to make the point very obvious, consider bins that do not have the same
108+
# spacing. By normalizing by density, we preserve the shape of the
109+
# distribution, whereas if we do not, then the wider bins have much higher
110+
# values than the thin bins:
111+
112+
fig, ax = plt.subplot_mosaic([['False', 'True']], layout='constrained')
113+
dx = 0.1
114+
xbins = np.hstack([np.arange(-4, -1.25, 6*dx), np.arange(-1.25, 4, dx)])
115+
ax['False'].hist(xdata, bins=xbins, density=False, histtype='step')
116+
ax['False'].set_ylabel('Count per bin')
117+
ax['False'].set_xlabel('x bins (below -1.25 bins are wider)')
118+
119+
ax['True'].hist(xdata, bins=xbins, density=True, histtype='step')
120+
ax['True'].plot(xpdf, pdf)
121+
ax['True'].set_ylabel('Probability per x')
122+
ax['True'].set_xlabel('x bins (below -1.25 bins are wider)')
123+
124+
125+
# %%
126+
# Using *density* also makes it easier to compare histograms with different bin
127+
# widths. Note that in order to get the theoretical distribution, we must
128+
# multiply the distribution by the number of data points and the bin width
129+
130+
fig, ax = plt.subplot_mosaic([['False', 'True']], layout='constrained')
131+
132+
# expected PDF
133+
ax['True'].plot(xpdf, pdf, '--', label='PDF', color='k')
134+
135+
for nn, dx in enumerate([0.1, 0.4, 1.2]):
136+
xbins = np.arange(-4, 4, dx)
137+
# expected histogram:
138+
ax['False'].plot(xpdf, pdf*1000*dx, '--', color=f'C{nn}')
139+
ax['False'].hist(xdata, bins=xbins, density=False, histtype='step')
140+
141+
ax['True'].hist(xdata, bins=xbins, density=True, histtype='step', label=dx)
142+
143+
# Labels:
144+
ax['False'].set_xlabel('x bins')
145+
ax['False'].set_ylabel('Count per bin')
146+
ax['True'].set_ylabel('Probability per x')
147+
ax['True'].set_xlabel('x bins')
148+
ax['True'].legend(fontsize='small')
149+
150+
# %%
151+
# Sometimes people want to normalize so that the sum of counts is one. This is
152+
# _not_ done with the *density* kwarg, but instead we can set the *weights* to
153+
# 1/N. Note, however, that the amplitude of the histogram still depends on
154+
# width of the bins
155+
156+
fig, ax = plt.subplots(layout='constrained', figsize=(3.5, 3))
157+
158+
for nn, dx in enumerate([0.1, 0.4, 1.2]):
159+
xbins = np.arange(-4, 4, dx)
160+
ax.hist(xdata, bins=xbins, weights=1/len(xdata) * np.ones(len(xdata)),
161+
histtype='step', label=f'{dx}')
162+
ax.set_xlabel('x bins')
163+
ax.set_ylabel('Bin count / N')
164+
ax.legend(fontsize='small')
165+
166+
# %%
167+
# The true value of normalizing is if you do want to compare two distributions
168+
# that have different sized populations:
169+
170+
xdata2 = rng.normal(size=100)
171+
172+
fig, ax = plt.subplot_mosaic([['no_norm', 'density', 'weight']],
173+
layout='constrained', figsize=(8, 4))
174+
175+
xbins = np.arange(-4, 4, 0.25)
176+
177+
ax['no_norm'].hist(xdata, bins=xbins, histtype='step')
178+
ax['no_norm'].hist(xdata2, bins=xbins, histtype='step')
179+
ax['no_norm'].set_ylabel('Counts')
180+
ax['no_norm'].set_xlabel('x bins')
181+
ax['no_norm'].set_title('No normalization')
182+
183+
ax['density'].hist(xdata, bins=xbins, histtype='step', density=True)
184+
ax['density'].hist(xdata2, bins=xbins, histtype='step', density=True)
185+
ax['density'].set_ylabel('Probabilty per x')
186+
ax['density'].set_title('Density=True')
187+
ax['density'].set_xlabel('x bins')
188+
189+
ax['weight'].hist(xdata, bins=xbins, histtype='step',
190+
weights=1 / len(xdata) * np.ones(len(xdata)),
191+
label='N=1000')
192+
ax['weight'].hist(xdata2, bins=xbins, histtype='step',
193+
weights=1 / len(xdata2) * np.ones(len(xdata2)),
194+
label='N=100')
195+
ax['weight'].set_xlabel('x bins')
196+
ax['weight'].set_ylabel('Counts / N')
197+
ax['weight'].legend(fontsize='small')
198+
ax['weight'].set_title('Weight = 1/N')
199+
200+
plt.show()
201+
202+
# %%
203+
#
204+
# .. admonition:: References
205+
#
206+
# The use of the following functions, methods, classes and modules is shown
207+
# in this example:
208+
#
209+
# - `matplotlib.axes.Axes.hist` / `matplotlib.pyplot.hist`
210+
# - `matplotlib.axes.Axes.set_title`
211+
# - `matplotlib.axes.Axes.set_xlabel`
212+
# - `matplotlib.axes.Axes.set_ylabel`
213+
# - `matplotlib.axes.Axes.legend`

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.