# -*- coding: utf-8 -*- """ Created on Wed Sep 1 16:30:23 2021 @author: Rene """ import numpy as np from scipy.stats import norm from scipy.stats import t import matplotlib.pyplot as plt def get_conf_int(x,alpha): n = len(x) x_bar = np.mean(x) st_dev_x_bar = np.std(x,ddof=1)/(n**0.5) half_width = t.ppf(1-(alpha),n-1)*st_dev_x_bar bounds = np.zeros(2) bounds[0] = -100000 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) 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') Figure = plt.figure() plt.figure(figsize=(10, 5)) 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' x_values = [conf_bounds[0], conf_bounds[1] ] y_values = [0.1,0.1] plt.plot(x_values,y_values,lw=1,ls='-',color=conf_color,label = 'Conf.Int') head_length = 0.005 x_values = [conf_bounds[1], conf_bounds[1] ] y_values = [0.1-head_length,0.1+head_length] plt.plot(x_values,y_values,lw=1,ls='-',color=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 " + f'{(100*(1-alpha)):2.0f}' + " % confidence interval - variance known" Figure.suptitle(text_str,size='14') plt.savefig('Confidence_Interval_Var_Unknown.png', dpi=1200) text_str = "Sampled " + f'{(100*(1-alpha)):2.0f}' + " % confidence interval - variance known" Figure.suptitle(text_str,size='14') plt.savefig('Lower_Confidence_Interval_Var_Unknown.png', dpi=300)