# -*- coding: utf-8 -*- """ Created on Sat Jan 8 15:19:57 2022 @author: Rene """ import numpy as np import matplotlib.pyplot as plt # Sampling from a discrete distribution with element and probabilities m = 100 elements = [1, 3, 4] probabilities = [3/5,1/5,1/5] sample = np.random.choice(elements, m, p=probabilities) # Transforming the Uniform Sample to a discrete distribution Sample y_points = np.zeros(len(elements)) for i in np.arange(0,len(elements)): y_points[i] = len(sample[sample == elements[i]])/m # Plotting the Uniform PDF and CDF plt.rc('font', family='serif', size='12') Figure = plt.figure(1) Figure.set_figwidth(9) Figure.set_figheight(5) Figure.subplots_adjust(left=0.1, bottom=0.1, right=0.95, top=0.85, hspace=0.1, wspace=0.25) #*************************************************************************************** LB_x = 0 UB_x = 4.25 off_set_x = 0.05*(UB_x-LB_x) x_lims = (LB_x-off_set_x,UB_x+off_set_x) LB_y = 0 UB_y = 1 off_set_y = 0.1*(UB_y-LB_y) y_lims = (LB_y-off_set_y,UB_y+off_set_y) Panel = Figure.add_subplot(1,1,1) plt.xlim(x_lims) plt.ylim(y_lims) plt.xlabel('x') plt.ylabel('Probability Mass Function $p(x)$') text_str = r'PMF - Example 6.2' plt.title(text_str) plt.axvline(0, lw=2, ls = '-',color = 'lightgray',alpha=0.5) plt.axhline(0, lw=2, ls = '-',color = 'lightgray',alpha=0.5) plt.scatter(elements,probabilities,color = 'red',alpha=0.5,s=100) text_str = r'sample size = '+ f'{m:0.0f}' plt.text(0.025,0.9,text_str,horizontalalignment = 'left',verticalalignment = 'center', color = 'red') for i in np.arange(0,3): text_str = f'{probabilities[i]:0.2f}' plt.text(elements[i]+0.1,probabilities[i],text_str,horizontalalignment = 'left',verticalalignment = 'center', color = 'green') x_values = [elements[i], elements[i]] y_values = [0, probabilities[i]] plt.plot(x_values, y_values,color='red',lw=5,alpha=0.5) x_values = [elements[i], elements[i]] y_values = [0, y_points[i]] plt.plot(x_values, y_values,color='blue',lw=2,alpha=0.5) plt.scatter(elements,y_points,color = 'blue',alpha = 0.5) text_str = r'$\widehat{p} = $'+ f'{y_points[i]:0.3f}' plt.text(elements[i]-0.1,y_points[i],text_str,horizontalalignment = 'right',verticalalignment = 'center', color = 'blue') plt.savefig('Question_6_2__Sampler.png', dpi=300)