# -*- coding: utf-8 -*- """ Created on Wed Sep 1 16:30:23 2021 @author: Rene """ import numpy as np from scipy.stats import norm import matplotlib.pyplot as plt def get_conf_int(x,alpha,sigma): n = len(x) x_bar = np.mean(x) st_dev_x_bar = sigma/(n**0.5) half_width = norm.ppf(1-(alpha/2),0,1)*st_dev_x_bar bounds = np.zeros(2) bounds[0] = x_bar-half_width bounds[1] = x_bar+half_width return(bounds) n = 10 the_mu = 0 the_sigma = 1 alpha = 0.10 x_points = np.linspace(0,1,100) LB = the_mu-4*the_sigma UB = the_mu+4*the_sigma x_points = (UB-LB)*x_points+LB y_points = norm.pdf(x_points,the_mu,the_sigma) sample = np.random.normal(the_mu, the_sigma, size = n) x_bar = np.mean(sample) conf_bounds = get_conf_int(sample,alpha,the_sigma) mu_in_conf = (conf_bounds[0] <= the_mu) and (conf_bounds[1] >= the_mu) # Plotting the analysis results LB = -3 UB = 3 off_set_x = 0.25 off_set_y = 0.01 max_y = 0.4 # Setting the attributes for the Figure plt.rc('font', family='serif', size='10') plt.figure(figsize=(10, 5)) Figure = plt.figure() Figure.subplots_adjust(hspace=0.4, wspace=0.4) x_lims = (LB-off_set_x,UB+off_set_x) y_lims = (0-off_set_y,max_y+off_set_y) plt.axvline(0, lw=2, ls = '-',color = 'lightgray',alpha=0.5) plt.axhline(0, lw=2, ls = '-',color = 'lightgray',alpha=0.5) plt.xlim(x_lims) plt.ylim(y_lims) plt.xlabel('x') plt.ylabel('density') plt.plot(x_points,y_points,ls='-',lw=0.5,label='N(0,1) pdf',color='blue') x_values = [the_mu, the_mu] y_values = [0, norm.pdf(the_mu,the_mu,the_sigma)] plt.plot(x_values,y_values,lw=0.5,ls='--',color='blue',label = 'True Average ' + '$\mu$') plt.scatter(sample,np.zeros(n),color="red", s = 10,label = 'sample') if mu_in_conf: conf_color = 'green' else: conf_color = 'red' half_width = (conf_bounds[1] - conf_bounds[0])/2 plt.errorbar(x_bar, 0.1, xerr = half_width, ecolor=conf_color, elinewidth=1, capsize=3,fmt='-o',ms=3,mfc=conf_color,mec=conf_color, label = 'conf.int', c = conf_color); x_values = [x_bar, x_bar] y_values = [0, 0.1] plt.plot(x_values,y_values,lw=0.5,ls='--',color='black') text_str = '$\overline{x}$' plt.text(x_bar,0.11,text_str) text_str = 'Sample Size = ' +str(n) plt.text(-3,0.35,text_str,color='red') plt.legend(loc = 'best') text_str = "Sampled " + str(100*(1-alpha)) + " % confidence interval - variance known" Figure.suptitle(text_str,size='14') plt.savefig('Confidence_Interval_Var_Known.png', dpi=1200)