Skip to content

Commit b87f2ca

Browse files
Merge pull request #856 from realpython/maintenance/python-histograms-20260920
Sync histograms with the updated tutorial
2 parents 26eff60 + c71a944 commit b87f2ca

2 files changed

Lines changed: 22 additions & 12 deletions

File tree

‎histograms/histograms.py‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313

1414
import random
1515
import sys
16-
import warnings
1716
from collections import Counter
1817

1918
import matplotlib.pyplot as plt
@@ -86,14 +85,20 @@ def ascii_histogram(seq) -> None:
8685
print("bin_edges:", bin_edges)
8786

8887
bcounts = np.bincount(a)
89-
hist, _ = np.histogram(a, range=(0, max(a)), bins=max(a) + 1)
88+
hist, _ = np.histogram(a, range=(0, np.max(a)), bins=np.max(a) + 1)
9089
print(bcounts)
9190
assert np.array_equal(hist, bcounts), "Bincounts unequal."
9291

9392
# Reproducing `collections.Counter`
9493
print(
9594
"Reproducing `collections.Counter`:",
96-
dict(zip(np.unique(a), bcounts[bcounts.nonzero()], strict=False)),
95+
dict(
96+
zip(
97+
np.unique(a).tolist(),
98+
bcounts[bcounts.nonzero()].tolist(),
99+
strict=False,
100+
)
101+
),
97102
)
98103

99104

@@ -191,17 +196,17 @@ def ascii_histogram(seq) -> None:
191196
# ---------------------------------------------------------------------
192197

193198
sns.set_style("darkgrid")
194-
# Suppress the kwarg warning related to normed/density from Matplotlib.
195-
with warnings.catch_warnings():
196-
warnings.simplefilter("ignore", category=UserWarning)
199+
sns.histplot(d, kde=True)
200+
plt.title("Seaborn's histplot()")
201+
plt.show()
197202

198-
sns.distplot(d)
199-
plt.title("Seaborn's distplot()")
200-
plt.show()
203+
params = stats.laplace.fit(d)
204+
x_laplace = np.linspace(d.min(), d.max(), num=250)
201205

202-
sns.distplot(d, fit=stats.laplace, kde=False)
203-
plt.title("Histogram with Fitted Laplace Distribution")
204-
plt.show()
206+
ax = sns.histplot(d, stat="density")
207+
ax.plot(x_laplace, stats.laplace.pdf(x_laplace, *params))
208+
plt.title("Histogram with Fitted Laplace Distribution")
209+
plt.show()
205210

206211

207212
data = np.random.choice(

‎histograms/requirements.txt‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
matplotlib==3.11.2
2+
numpy==2.5.3
3+
pandas==3.0.6
4+
scipy==1.18.1
5+
seaborn==0.13.2

0 commit comments

Comments
 (0)