Plot a Normal Distribution in Python with scipy and Matplotlib

Plot a normal distribution in Python with scipy.stats.norm.pdf and Matplotlib: shade the 68-95-99.7 rule, overlay a fitted curve on a histogram, and read probabilities from the CDF.

To plot a normal distribution in Python, build an x grid with np.linspace(), compute the density with scipy.stats.norm.pdf(x, loc=mean, scale=std), and draw it with ax.plot(). loc is the mean and scale is the standard deviation (not the variance). The same norm object also gives you the CDF, percentiles and random samples, which the sections below use.

Quick Example

The numbers here are adult heights in centimeters, with a mean of 170 and a standard deviation of 7.

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

mu, sigma = 170, 7
x = np.linspace(mu - 4 * sigma, mu + 4 * sigma, 400)
y = norm.pdf(x, loc=mu, scale=sigma)

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(x, y, color="#264653", linewidth=2)
ax.fill_between(x, y, where=(x >= mu - sigma) & (x <= mu + sigma), color="#2a9d8f", alpha=0.35,
                label="Within 1 standard deviation")
ax.axvline(mu, color="#264653", linestyle="--", linewidth=1)
ax.set_xlabel("Height (cm)")
ax.set_ylabel("Probability density")
ax.set_title("Normal distribution, mean 170 cm, standard deviation 7 cm")
ax.legend()
plt.show()

A bell curve centered at 170 centimeters with the area within one standard deviation of the mean shaded teal

The curve peaks at the mean, where the density is 0.057 (that is 1 / (7 * sqrt(2 * pi))). The y-axis is a density, not a probability. A single height has probability zero, and the probability of a range is the area under the curve over that range.

How do I plot several normal distributions together?

Loop over parameter pairs and call norm.pdf() for each. The mean moves the curve left and right, and the standard deviation sets how wide and flat it is. Every curve still has an area of 1, so a wider curve has to be shorter:

settings = [(170, 5), (170, 7), (170, 12), (182, 7)]
colors = ["#264653", "#2a9d8f", "#e9c46a", "#e76f51"]

fig, ax = plt.subplots(figsize=(8, 4.5))
x = np.linspace(135, 215, 500)
for (m, s), color in zip(settings, colors):
    ax.plot(x, norm.pdf(x, m, s), color=color, linewidth=2, label=f"mean {m}, sd {s}")
ax.set_xlabel("Height (cm)")
ax.set_ylabel("Probability density")
ax.legend()
plt.show()

Four bell curves: three centered at 170 with standard deviations 5, 7 and 12, and one centered at 182 with standard deviation 7

The sd 5 curve peaks at 0.080 and the sd 12 curve at 0.033. The mean 182 curve is the sd 7 curve shifted 12 cm to the right, with the same shape and the same peak height.

How do I shade the 68-95-99.7 rule?

About 68% of a normal distribution lies within one standard deviation of the mean, 95% within two and 99.7% within three. Draw the bands from widest to narrowest so the darker ones sit on top, and get the exact shares from norm.cdf():

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(x, norm.pdf(x, mu, sigma), color="#264653", linewidth=2)

for k, color in [(3, "#cfe8e4"), (2, "#8fcfc6"), (1, "#2a9d8f")]:
    share = norm.cdf(k) - norm.cdf(-k)
    ax.fill_between(x, norm.pdf(x, mu, sigma),
                    where=(x >= mu - k * sigma) & (x <= mu + k * sigma),
                    color=color, label=f"±{k} sd: {share:.1%}")
ax.set_xlabel("Height (cm)")
ax.set_ylabel("Probability density")
ax.legend()
plt.show()

A bell curve with nested shaded bands for within one, two and three standard deviations, labeled 68.3%, 95.4% and 99.7%

The exact shares are 68.3%, 95.4% and 99.7%. norm.cdf(k) - norm.cdf(-k) uses the standard normal (mean 0, sd 1), which is fine here because the share inside ±k standard deviations does not depend on the mean or the sd.

How do I overlay a normal curve on a histogram?

Fit the mean and standard deviation with norm.fit(), then plot the histogram with density=True so its area matches the curve. This is the quickest visual check of whether data looks normal. Here 500 simulated heights are drawn with rng.normal():

rng = np.random.default_rng(5)
heights = rng.normal(170, 7, 500)

fit_mu, fit_sigma = norm.fit(heights)  # maximum likelihood estimates

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.hist(heights, bins=25, density=True, color="#a8dadc", edgecolor="white", label="500 heights")
grid = np.linspace(heights.min() - 5, heights.max() + 5, 400)
ax.plot(grid, norm.pdf(grid, fit_mu, fit_sigma), color="#e76f51", linewidth=2,
        label=f"Fitted normal (mean {fit_mu:.1f}, sd {fit_sigma:.1f})")
ax.set_xlabel("Height (cm)")
ax.set_ylabel("Density")
ax.set_ylim(0, 0.078)  # headroom for the legend
ax.legend(loc="upper right")
plt.show()

Histogram of 500 simulated heights with a fitted normal curve on top that follows the bars closely

norm.fit() returns the sample mean and the standard deviation with ddof=0 (6.71 here). np.std(heights, ddof=1) gives a slightly larger 6.72, which is the usual sample estimate. With 500 values the difference is invisible, but it matters for small samples. If the histogram and curve disagree, a Q-Q plot shows where. The seaborn histplot guide covers the histogram side, including kde=True for a smoothed curve that makes no normality assumption.

How do I get probabilities from a normal distribution?

Four methods cover most questions. cdf(x) is the probability of a value at or below x, sf(x) is the probability above x (1 - cdf, but more accurate in the far tail), ppf(q) is the inverse of the CDF (the value with a share q below it), and rvs() draws random samples.

dist = norm(loc=170, scale=7)  # "freeze" the parameters once

print(f"P(height > 180)        = {dist.sf(180):.3f}")
print(f"P(160 < height < 180)  = {dist.cdf(180) - dist.cdf(160):.3f}")
print(f"Middle 95% of heights  = {dist.ppf(0.025):.1f} to {dist.ppf(0.975):.1f} cm")
print(f"Tallest 5% start at    = {dist.ppf(0.95):.1f} cm")
P(height > 180)        = 0.077
P(160 < height < 180)  = 0.847
Middle 95% of heights  = 156.3 to 183.7 cm
Tallest 5% start at    = 181.5 cm

Freezing the distribution with norm(loc=170, scale=7) saves repeating the parameters on every call. The 500 simulated heights agree: 7.2% are above 180 cm, against 7.7% from the formula.

To see a probability, plot the density and the CDF side by side and shade the matching region on each. The area under the density to the right of 180 equals the gap between the CDF and 1:

x = np.linspace(135, 205, 500)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))

ax1.plot(x, dist.pdf(x), color="#264653", linewidth=2)
ax1.fill_between(x, dist.pdf(x), where=x >= 180, color="#e76f51", alpha=0.6,
                 label=f"P(height > 180) = {dist.sf(180):.3f}")
ax1.set_title("Density (pdf)")
ax1.set_xlabel("Height (cm)")
ax1.set_ylim(0, 0.07)  # headroom for the legend
ax1.legend(loc="upper right")

ax2.plot(x, dist.cdf(x), color="#264653", linewidth=2)
ax2.axvline(180, color="#e76f51", linestyle="--")
ax2.axhline(dist.cdf(180), color="#e76f51", linestyle="--")
ax2.set_title(f"Cumulative (cdf): P(height ≤ 180) = {dist.cdf(180):.3f}")
ax2.set_xlabel("Height (cm)")
plt.tight_layout()
plt.show()

Two panels: the normal density with the area above 180 centimeters shaded orange, and the cumulative curve with dashed lines marking 180 centimeters and a probability of 0.923

Which scipy method do I use?

You want Method Example
The curve to plot norm.pdf(x, loc, scale) norm.pdf(x, 170, 7)
Probability of a value at or below x norm.cdf(x, loc, scale) norm.cdf(180, 170, 7)
Probability above x norm.sf(x, loc, scale) norm.sf(180, 170, 7)
The value for a given percentile norm.ppf(q, loc, scale) norm.ppf(0.95, 170, 7)
A central interval norm.interval(0.95, loc, scale) (156.3, 183.7)
Random samples norm.rvs(loc, scale, size, random_state) or rng.normal(loc, scale, size) rng.normal(170, 7, 500)
Mean and sd from data norm.fit(data) norm.fit(heights)

rng.normal() is the fastest way to simulate, and norm.rvs(random_state=rng) gives the same draws through scipy. This post used scipy 1.18 and Matplotlib 3.11.

Practical Tips

  • scale is the standard deviation. If you have a variance, pass np.sqrt(variance).
  • Peak heights above 1 are fine. A density is not a probability, so a narrow curve (sd 0.2) peaks near 2.
  • Cover about ±4 standard deviations on the x grid. Narrower cuts off the tails and wider wastes space.
  • Use 300 or more grid points (np.linspace(..., 400)) so the curve looks smooth rather than faceted.
  • Real data is rarely this tidy. Skewed or heavy-tailed data needs a different distribution, as in stock returns, where a fitted normal badly understates the extremes.

Similar Topics