Learn Python Programming  /  Data Visualization  /  Histogram

Histogram

plt.hist() bins numeric data and shows how many observations fall into each bin — the standard way to see a variable's overall shape, spread, and skew.

A Basic Histogram

R Code
import numpy as np

np.random.seed(1)
x = np.random.normal(loc=50, scale=10, size=500)

plt.hist(x, color="lightgreen", edgecolor="black")
plt.title("Distribution of X")
plt.show()

Controlling the Number of Bins

R Code
plt.hist(x, bins=10, color="skyblue")
plt.show()

plt.hist(x, bins=50, color="skyblue")
plt.show()

Overlaying a Density Curve with Seaborn

R Code
import seaborn as sns

sns.histplot(x, kde=True, color="lightgreen")
plt.title("Histogram with Density Curve")
plt.show()

Advanced: Comparing Two Distributions

🚀 Advanced Example
Overlapping two semi-transparent histograms on the same axes is a quick way to visually compare two groups.
R Code
group_a = np.random.normal(50, 8, 300)
group_b = np.random.normal(60, 8, 300)

plt.hist(group_a, alpha=0.5, label="Group A", color="blue")
plt.hist(group_b, alpha=0.5, label="Group B", color="red")
plt.legend()
plt.show()

Key Points

  • plt.hist(data, bins=n) bins numeric data and shows how many values fall into each bin.
  • seaborn.histplot(data, kde=True) adds a smooth density curve on top of the histogram automatically.
  • alpha= (transparency) lets you overlay two histograms for a direct visual comparison.