import matplotlib.pyplot as plt
import numpy as np
import scipy.stats
# Create the Student's t distribution.
mu, sigma, nu = 0.0, 1.0, 4.0
student_t = scipy.stats.t(nu, loc=mu, scale=sigma)
pdf = student_t.pdf
cdf = student_t.cdf
inverse_cdf = student_t.ppf
# Compute the critical region.
p_value = 0.05
lower_boundary = inverse_cdf(p_value / 2)
upper_boundary = inverse_cdf(1 - p_value / 2)
# Sanity check the computed region with the CDF.
assert np.allclose(cdf(lower_boundary), p_value / 2)
assert np.allclose(cdf(upper_boundary) - cdf(lower_boundary), 1.0 - p_value)
assert np.allclose(1.0 - cdf(upper_boundary), p_value / 2)
print "Critical regions: d < {0}, d > {1}".format(lower_boundary, upper_boundary)
Critical regions: d < -2.7764451052, d > 2.7764451052
# Plot the PDF and color in the critical regions.
x = np.linspace(-4, 4, num=1000)
y_pdf = pdf(x)
plt.plot(x, y_pdf)
plt.xlim(-4, 4)
plt.fill_between(x, 0, y_pdf, where=(x < lower_boundary))
plt.fill_between(x, 0, y_pdf, where=(x > upper_boundary))
<matplotlib.collections.PolyCollection at 0xad4aaec>