Skip to content

Instantly share code, notes, and snippets.

@AdamSpannbauer
Created February 26, 2020 13:45
Show Gist options
  • Save AdamSpannbauer/aea3163f6005952de5f27b6fd87d85b1 to your computer and use it in GitHub Desktop.
Save AdamSpannbauer/aea3163f6005952de5f27b6fd87d85b1 to your computer and use it in GitHub Desktop.
# Modified from https://www.science-emergence.com/Articles/How-to-plot-a-normal-distribution-with-matplotlib-in-python-/
import numpy as np
import scipy.stats
import matplotlib.pyplot as plt
def plot_area(mean, std, pt1, pt2, fill):
plt.plot([pt1, pt1], [0.0, scipy.stats.norm.pdf(pt1, mean, std)], color='black')
plt.plot([pt2, pt2], [0.0, scipy.stats.norm.pdf(pt2, mean, std)], color='black')
ptx = np.linspace(pt1, pt2, 10)
pty = scipy.stats.norm.pdf(ptx, mean, std)
plt.fill_between(ptx, pty, color=fill, alpha='1.0')
def plot_normal(mean=0, std=1, xmin=-5, xmax=5, breaks=np.array([1, 2, 3, 10]),
fills=['#0b559f', '#2b7bba', '#539ecd', '#89bedc']):
x = np.linspace(xmin, xmax, 100)
y = scipy.stats.norm.pdf(x, mean, std)
plt.plot(x, y, color='black')
pt1 = mean + breaks[0] * std
pt2 = mean - breaks[0] * std
plot_area(mean, std, pt1, pt2, fill=fills[0])
for i in range(breaks.size - 1):
pt1 = mean + breaks[i] * std
pt2 = mean + breaks[i + 1] * std
plot_area(mean, std, pt1, pt2, fill=fills[i + 1])
pt1 = mean - breaks[i] * std
pt2 = mean - breaks[i + 1] * std
plot_area(mean, std, pt1, pt2, fill=fills[i + 1])
plt.grid()
plt.xlim(xmin, xmax)
plt.title('Normal Distribution', fontsize=10)
plt.xlabel('x')
plt.ylabel('p(x)')
plt.show()
plot_normal(8, 3, -3, 19)
plot_normal()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment