Home > Software design >  python shading the 95% confidence areas under a normal distribution
python shading the 95% confidence areas under a normal distribution

Time:10-20

I have the following normal distribution plot

x_axis = np.arange(-10, 10, 0.001)
pdf = stats.norm.pdf(x_axis, np.mean(x_axis), np.std(x_axis))
plt.plot(x_axis, pdf)

I would like to shade/highlight the 95% confidence interval under the normal distribution. I would also like to label the 95% upper limit and lower limit value on the x-axis.

Help is much appreciated!

CodePudding user response:

You can use plt.fill_between.

I used here the standard normal distribution (0,1) as your calculation on x_axis would make the displayed range too narrow to see the fill.

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

x_axis = np.arange(-10, 10, 0.001)

avg = 0
std = 1

pdf = stats.norm.pdf(x_axis, avg, std)
plt.plot(x_axis, pdf)

std_lim = 1.96 # 95% CI
low = avg-std_lim*std
high = avg std_lim*std

plt.fill_between(x_axis, pdf, where=(low < x_axis) & (x_axis < high))
plt.text(low, 0, low, ha='center')
plt.text(high, 0, high, ha='center')

95 CI

  • Related