Matplotlib Histograms
Understand distributions, detect skew, and compare datasets with Matplotlib histograms.
Basic Histogram
fig, ax = plt.subplots()
ax.hist(samples, bins=20, color="#2563eb", edgecolor="white")
ax.set_xlabel("Value")
ax.set_ylabel("Frequency")Use bins to control bucket count; more bins provide detail while fewer keep the chart readable.
Density Normalization
Set density=True to display probability density instead of counts.
ax.hist(samples, bins=30, density=True, alpha=0.6)
ax.set_ylabel("Density")Overlaying Distributions
Compare multiple datasets by stacking or overlaying with transparency.
ax.hist(group_a, bins=25, alpha=0.5, label="Group A")
ax.hist(group_b, bins=25, alpha=0.5, label="Group B")
ax.legend()Ensure bins align across datasets for accurate comparisons.
Cumulative Histograms
Reveal cumulative distribution functions (CDF) by enabling cumulative=True.
ax.hist(samples, bins=30, cumulative=True, histtype="step")Use step plots to avoid obscuring data points.
Styling Considerations
- Set
edgecolorfor crisp separation between bars. - Annotate mean and median with vertical lines using
ax.axvline(). - Share bin policies with the team via
info.studygrid@gmail.comfor consistent reporting.
Next Steps
Wrap up the Matplotlib series by creating pie charts for categorical proportions.
Bars vs Histograms
A bar chart compares categories; a histogram shows the distribution of one numeric variable by grouping values into bins.
import matplotlib.pyplot as plt
import numpy as np
data = np.random.normal(170, 10, 250) # 250 heights
plt.hist(data, bins=20, edgecolor="white")
plt.xlabel("height (cm)")
plt.ylabel("count")
plt.show()The bins argument controls detail: too few hides structure, too many makes it noisy. Start around 10–30 and adjust.
Try It Yourself
Exercise: Plot a histogram of 1000 random values from a normal distribution.
Show solution
import matplotlib.pyplot as plt
import numpy as np
plt.hist(np.random.normal(0, 1, 1000), bins=25)
plt.show()Key Takeaways
- Histograms show the distribution of numeric data.
- Tune
binsto balance detail and noise. - Use bar charts for categories, histograms for distributions.
📘 Real-World Deep Dive
Knowing <strong>Matplotlib Histograms (Matplotlib)</strong> well is what turns Matplotlib from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of Matplotlib Histograms that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
import matplotlib.pyplot as plt
import numpy as np
data = np.random.normal(0, 1, 1000)
plt.hist(data, bins=30, alpha=0.7)
plt.title("Standard normal"); plt.show()Expected Output
(no output)Common mistakes
- Calling
plt.plotwithoutplt.show()in scripts (orplt.savefig) produces no visible output. - Passing mismatched array shapes to
plt.plot(x, y)raises a uselessValueError— verify shapes withx.shapeandy.shapefirst. - Mixing
numpy.float64withpandas.Seriesis OK, but mixingnumpy.datetime64with Pythondatetime.dateneeds an explicit cast. - Treating Matplotlib Histograms as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- For large scatter plots use
plt.scatter(..., s=1, rasterised=True)or switch todatashader. - Use the
aggbackend on web services:import matplotlib; matplotlib.use("Agg"). - Plot once and reuse the figure: avoid embedding Matplotlib into tight Python loops without an explicit
clear(). - When working with Matplotlib, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.