我们从Python开源项目中,提取了以下30个代码示例,用于说明如何使用matplotlib.mlab.normpdf()。
def histograms_plot(): """ histograms plot """ # ?????? mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) # ?????? num_bins = 50 # ????,??????? n, bins, patches = plt.hist(x, bins=num_bins, normed=1, color="green", alpha=0.6, label="hist") # ??????????,???? y = mlab.normpdf(bins, mu, sigma) plt.plot(bins, y, "r--", label="line") # ?????? plt.legend(loc="upper left", shadow=True) # ???? plt.show() return # histograms_plot()
def compute_coarse_coding_features(self, num_states): assert num_states == 3 npoints = 600 cc_features = numpy.zeros((num_states, npoints)) x1 = numpy.linspace(-1.5, 1.5, npoints) x2 = numpy.linspace(-1.0, 2.0, npoints) x3 = numpy.linspace(-0.5, 2.5, npoints) mu1 = 0.0 mu2 = 0.5 mu3 = 1.0 sigma = 0.4 cc_features[0, :] = mlab.normpdf(x1, mu1, sigma) cc_features[1, :] = mlab.normpdf(x2, mu2, sigma) cc_features[2, :] = mlab.normpdf(x3, mu3, sigma) return cc_features
def plotState(self, state, f_color=False): """ Plot a state to the screen """ num_mean = state.mean num_sigma = state.std if num_sigma == 0: # this is just for hacking plt.plot([num_mean, num_mean], [0, self.ylim]) return arr_x = np.linspace(num_mean-5*num_sigma, num_mean+5*num_sigma, 100) # normpdf uses mu, sigma for normal distribution function # to produce the y axis for x # should I consider prior? arr_y = mlab.normpdf(arr_x, num_mean, num_sigma) if f_color: self.axis.fill_between(arr_x, arr_y) self.axis.plot(arr_x, arr_y) # override
def extract_coarse_coding_features_absolute(self, phone_duration): dur = int(phone_duration) cc_feat_matrix = numpy.zeros((dur, 3)) npoints1 = (dur*2)*10+1 npoints2 = (dur-1)*10+1 npoints3 = (2*dur-1)*10+1 x1 = numpy.linspace(-dur, dur, npoints1) x2 = numpy.linspace(1, dur, npoints2) x3 = numpy.linspace(1, 2*dur-1, npoints3) mu1 = 0 mu2 = (1+dur)/2 mu3 = dur variance = 1 sigma = variance*((dur/10)+2) sigma1 = sigma sigma2 = sigma-1 sigma3 = sigma y1 = mlab.normpdf(x1, mu1, sigma1) y2 = mlab.normpdf(x2, mu2, sigma2) y3 = mlab.normpdf(x3, mu3, sigma3) for i in range(dur): cc_feat_matrix[i,0] = y1[(dur+1+i)*10] cc_feat_matrix[i,1] = y2[i*10] cc_feat_matrix[i,2] = y3[i*10] for i in range(3): cc_feat_matrix[:,i] = cc_feat_matrix[:,i]/max(cc_feat_matrix[:,i]) return cc_feat_matrix ### this function is not used now
def plot_z(self,indices=None,figsize=(15,5),loc=1): import matplotlib.pyplot as plt import matplotlib.mlab as mlab import seaborn as sns plt.figure(figsize=figsize) for z in range(1,len(self.z_list)+1): if indices is not None and z-1 not in indices: continue else: if hasattr(self.z_list[z-1], 'sample'): sns.distplot(self.z_list[z-1].prior.transform(self.z_list[z-1].sample), rug=False, hist=False,label=self.z_list[z-1].method + ' estimate of ' + self.z_list[z-1].name) elif hasattr(self.z_list[z-1], 'value') and hasattr(self.z_list[z-1], 'std'): if self.z_list[z-1].prior.transform_name is None: x = np.linspace(self.z_list[z-1].value-self.z_list[z-1].std*3.5,self.z_list[z-1].value+self.z_list[z-1].std*3.5,100) plt.plot(x,mlab.normpdf(x,self.z_list[z-1].value,self.z_list[z-1].std),label=self.z_list[z-1].method + ' estimate of ' + self.z_list[z-1].name) else: sims = self.z_list[z-1].prior.transform(np.random.normal(self.z_list[z-1].value,self.z_list[z-1].std,100000)) sns.distplot(sims, rug=False, hist=False,label=self.z_list[z-1].method + ' estimate of ' + self.z_list[z-1].name) else: raise ValueError("No information on latent variable to plot!") plt.xlabel('Value') plt.ylabel('Frequency') plt.title('Latent Variable Plot') plt.legend(loc=1) plt.show()
def _rerender(self): nmr_maps = len(self.maps_to_show) if self._show_trace: nmr_maps *= 2 grid = GridSpec(nmr_maps, 1, left=0.04, right=0.96, top=0.94, bottom=0.06, hspace=0.2) i = 0 for map_name in self.maps_to_show: samples = self._voxels[map_name] if self._sample_indices is not None: samples = samples[:, self._sample_indices] title = map_name if map_name in self.names: title = self.names[map_name] if isinstance(self._nmr_bins, dict) and map_name in self._nmr_bins: nmr_bins = self._nmr_bins[map_name] else: nmr_bins = self._nmr_bins hist_plot = plt.subplot(grid[i]) n, bins, patches = hist_plot.hist(np.nan_to_num(samples[self.voxel_ind, :]), nmr_bins, normed=True) plt.title(title) i += 1 if self._fit_gaussian: mu, sigma = norm.fit(samples[self.voxel_ind, :]) bincenters = 0.5*(bins[1:] + bins[:-1]) y = mlab.normpdf(bincenters, mu, sigma) hist_plot.plot(bincenters, y, 'r', linewidth=1) if self._show_trace: trace_plot = plt.subplot(grid[i]) trace_plot.plot(samples[self.voxel_ind, :]) i += 1
def extract_coarse_coding_features_absolute(self, phone_duration): dur = int(phone_duration) cc_feat_matrix = numpy.zeros((dur, 3)) npoints1 = (dur*2)*10+1 npoints2 = (dur-1)*10+1 npoints3 = (2*dur-1)*10+1 x1 = numpy.linspace(-dur, dur, npoints1) x2 = numpy.linspace(1, dur, npoints2) x3 = numpy.linspace(1, 2*dur-1, npoints3) mu1 = 0 mu2 = (1+dur)/2 mu3 = dur variance = 1 sigma = variance*((dur/10)+2) sigma1 = sigma sigma2 = sigma-1 sigma3 = sigma y1 = mlab.normpdf(x1, mu1, sigma1) y2 = mlab.normpdf(x2, mu2, sigma2) y3 = mlab.normpdf(x3, mu3, sigma3) for i in xrange(dur): cc_feat_matrix[i,0] = y1[(dur+1+i)*10] cc_feat_matrix[i,1] = y2[i*10] cc_feat_matrix[i,2] = y3[i*10] for i in xrange(3): cc_feat_matrix[:,i] = cc_feat_matrix[:,i]/max(cc_feat_matrix[:,i]) return cc_feat_matrix ### this function is not used now
def plot_rbf_kernel(): """ plot RBF kernel :return: """ plt.subplot(4, 2, 1) mu = 3 variance = 1 sigma = np.sqrt(variance) x = np.linspace(mu - 3 * variance, mu + 3 * variance, 100) plt.plot(x, mlab.normpdf(x, mu, sigma)) plt.title('RBF kernel')
def dist_plot(rating_df): x = np.linspace(0, 50, 500) data_dict = {} for row in rating_df.iterrows(): label_name = (row[1]['first_name'] + ' ' + row[1]['last_name'][0] + '.') data_dict[label_name] = (x, mlab.normpdf(x, row[1]['rating'], row[1]['sigma'])) final_df = pd.DataFrame() for k, v in data_dict.iteritems(): final_df[k] = v[1] final_df['index'] = x final_df.set_index('index', inplace=True) trace_dict = dict() for n, col in enumerate(final_df.columns): trace_dict[n] = go.Scatter( x=final_df.index, y=final_df[col], name=col ) data = trace_dict.values() # Edit the layout layout = dict(title='Individual Gaussian Skill Distribution', xaxis=dict(title='Mu'), yaxis=dict(title='Value'), height=750 ) return offl.plot(dict(data=data, layout=layout), output_type='div')
def update(self): num_mu = self.scmodel.mu # compute sigma num_sigma = math.sqrt(self.scmodel.var) array_x = np.linspace(num_mu - 3*num_sigma,num_mu + 3*num_sigma,100) array_y = mlab.normpdf(array_x,num_mu,num_sigma) self.axis.fill_between(array_x, array_y) self.axis.plot(array_x, array_y)
def kalman_plot(prediction, measurement, correction): """Helper to draw all curves in each filter step.""" plot([normpdf(x, prediction.mu, sqrt(prediction.sigma2)) for x in range(*arena)], color = 'b', linewidth=2) plot([normpdf(x, measurement.mu, sqrt(measurement.sigma2)) for x in range(*arena)], color = 'g', linewidth=2) plot([normpdf(x, correction.mu, sqrt(correction.sigma2)) for x in range(*arena)], color = 'r', linewidth=2) # # Histogram filter step. #
def plot_distribution(self, mean, sigma, array): vlines = [mean-(1*sigma), mean, mean+(1*sigma)] for val in vlines: plt.axvline(val, color='k', linestyle='--') bins = np.linspace(mean-(4*sigma), mean+(4*sigma), 200) plt.hist(array, bins, alpha=0.5) y = mlab.normpdf(bins, mean, sigma) plt.plot(bins, y, 'r--') plt.subplots_adjust(left=0.15) plt.show() print(mean, sigma)
def plot_distribution(self, mean, sigma, array): vlines = [mean-(1*sigma), mean, mean+(1*sigma)] for val in vlines: plt.axvline(val, color='k', linestyle='--') bins = np.linspace(mean-(4*sigma), mean+(4*sigma), 200) plt.hist(array, bins, alpha=0.5) y = mlab.normpdf(bins, mean, sigma) plt.plot(bins, y, 'r--') plt.subplots_adjust(left=0.15) plt.show() print mean, sigma
def percent_change_as_hist(adjusted_df, security): """ This function visualizes the percentage change data as a histogram. The graph is also fitted to a normal distribution curve. :param security: <SecurityInfo class> Holds information about the requested security :param adjusted_df: Pandas DataFrame with columns: Date, Adjusted Close, and Percentage Change. """ pct_change_list = adjusted_df['Percentage Change'] # Code below removes the NaN value and plots the histogram. Bins are left adjusted right now, so when plotting the # normal distribution function, we must adjust it to be based off the center (average) of the bins. n, bins, patches = plt.hist(pct_change_list.dropna(), bins=25, normed=True) bincenters = 0.5*(bins[1:]+bins[:-1]) plt.xlabel("Percentage change") plt.ylabel("Frequency") mean, std = get_params_for_norm_dist(adjusted_df) plt.title("Distribution of percentage change in " + security.get_name() + " Mu: %.3f, Sigma: %.3f" % (mean, std), y=1.03) # adds vertical lines to the graph corresponding to the x's that represent the number of deviations from the mean for num_std_from_mean in range(-3, 4): plt.axvline(mean + std * num_std_from_mean) # plots the normal pdf of best fit y = mlab.normpdf(bincenters, mean, std) plt.plot(bincenters, y, 'r--', linewidth=1) plt.show()
def show_rand_walks(all_walks, security): """ Visualizes all random walks as a plot and distribution. :param all_walks: list of all random walks conducted :param security: holds information about the security """ np_aw = np.array(all_walks) # converts the list of all random walks to a Numpy Array np_aw_t = np.transpose(np_aw) # must transpose the array for graph to display properly plt.clf() plt.plot(np_aw_t) plt.xlabel("Steps") plt.ylabel("Value of " + security.get_name()) plt.title("All Random Walks of " + security.get_name()) plt.show() # Select last row from np_aw_t: ends ends = np_aw_t[-1] # Plot histogram of ends, display plot n, bins, patches = plt.hist(ends, bins=25, normed=True) plt.xlabel("Final Value of " + security.get_name() + " at end of period.") plt.ylabel("Frequency") rand_mean = ends.mean() rand_std = ends.std() plt.title("Distribution of Random Walk Final Values. Mean is %d and Standard Deviation is %d" % (rand_mean, rand_std), y=1.03) for num_std_from_mean in range(-3, 4): plt.axvline(rand_mean + rand_std * num_std_from_mean) bincenters = 0.5*(bins[1:]+bins[:-1]) # plots the normal pdf of best fit y = mlab.normpdf(bincenters, rand_mean, rand_std) plt.plot(bincenters, y, 'r--', linewidth=3) plt.show()
def show_rand_walks(all_walks, security): """ Visualizes all random walks as a plot and distribution. :param all_walks: list of all random walks conducted """ np_aw = np.array(all_walks) # converts the list of all random walks to a Numpy Array np_aw_t = np.transpose(np_aw) # must transpose the array for graph to display properly plt.clf() plt.plot(np_aw_t) plt.xlabel("Steps") plt.ylabel("Value of " + security.get_name()) plt.title("All Random Walks of " + security.get_name()) plt.show() # Select last row from np_aw_t: ends ends = np_aw_t[-1] # Plot histogram of ends, display plot n, bins, patches = plt.hist(ends, bins=25, normed=True) plt.xlabel("Final Value of " + security.get_name() + " at end of period.") plt.ylabel("Frequency") rand_mean = ends.mean() rand_std = ends.std() plt.title("Distribution of Random Walk Final Values. Mean is %d and Standard Deviation is %d" % (rand_mean, rand_std), y=1.03) for num_std_from_mean in range(-3, 4): plt.axvline(rand_mean + rand_std * num_std_from_mean) bincenters = 0.5*(bins[1:]+bins[:-1]) # plots the normal pdf of best fit y = mlab.normpdf(bincenters, rand_mean, rand_std) plt.plot(bincenters, y, 'r--', linewidth=3) plt.show()
def percent_change_as_hist(adjusted_df): """ This function visualizes the percentage change data as a histogram. The graph is also fitted to a normal distribution curve. :param adjusted_df: Pandas DataFrame with columns: Date, Adjusted Close, and Percentage Change. """ pct_change_list = adjusted_df['Percentage Change'] # Code below removes the NaN value and plots the histogram. Bins are left adjusted right now, so when plotting the # normal distribution function, we must adjust it to be based off the center (average) of the bins. n, bins, patches = plt.hist(pct_change_list.dropna(), bins=25, normed=True) bincenters = 0.5*(bins[1:]+bins[:-1]) plt.xlabel("Percentage change") plt.ylabel("Frequency") mean, std = get_params_for_norm_dist(adjusted_df) plt.title("Distribution of percentage change in S&P 500. Mu: %.3f, Sigma: %.3f" % (mean, std), y=1.03) # adds vertical lines to the graph corresponding to the x's that represent the number of deviations from the mean for num_std_from_mean in range(-3, 4): plt.axvline(mean + std * num_std_from_mean) # plots the normal pdf of best fit y = mlab.normpdf(bincenters, mean, std) plt.plot(bincenters, y, 'r--', linewidth=1) plt.show()
def show_rand_walks(all_walks): """ Visualizes all random walks as a plot and distribution. :param all_walks: list of all random walks conducted """ np_aw = np.array(all_walks) # converts the list of all random walks to a Numpy Array np_aw_t = np.transpose(np_aw) # must transpose the array for graph to display properly plt.clf() plt.plot(np_aw_t) plt.xlabel("Steps") plt.ylabel("S&P 500 Index Value") plt.title("All Random Walks of the S&P 500 Index") plt.show() # Select last row from np_aw_t: ends ends = np_aw_t[-1] # Plot histogram of ends, display plot n, bins, patches = plt.hist(ends, bins=25, normed=True) plt.xlabel("Final S&P 500 Index Value at end of period.") plt.ylabel("Frequency") rand_mean = ends.mean() rand_std = ends.std() plt.title("Distribution of Random Walk Final Values. Mean is %d and Standard Deviation is %d" % (rand_mean, rand_std), y=1.03) for num_std_from_mean in range(-3, 4): plt.axvline(rand_mean + rand_std * num_std_from_mean) bincenters = 0.5*(bins[1:]+bins[:-1]) # plots the normal pdf of best fit y = mlab.normpdf(bincenters, rand_mean, rand_std) plt.plot(bincenters, y, 'r--', linewidth=3) plt.show()
def percent_change_as_hist(adjusted_df, security): """ This function visualizes the percentage change data as a histogram. The graph is also fitted to a normal distribution curve. :param security: <SecurityInfo class> Holds information about the requested security :param adjusted_df: Pandas DataFrame with columns: Date, Adj Close, and Percentage Change. """ pct_change_list = adjusted_df['Percentage Change'] # Code below removes the NaN value and plots the histogram. Bins are left adjusted right now, so when plotting the # normal distribution function, we must adjust it to be based off the center (average) of the bins. n, bins, patches = plt.hist(pct_change_list.dropna(), bins=25, normed=True) bincenters = 0.5*(bins[1:]+bins[:-1]) plt.xlabel("Percentage change") plt.ylabel("Frequency") mean, std = get_params_for_norm_dist(adjusted_df) plt.title("Distribution of percentage change in " + security.get_name() + " Mu: %.3f, Sigma: %.3f" % (mean, std), y=1.03) # adds vertical lines to the graph corresponding to the x's that represent the number of deviations from the mean for num_std_from_mean in range(-3, 4): plt.axvline(mean + std * num_std_from_mean) # plots the normal pdf of best fit y = mlab.normpdf(bincenters, mean, std) plt.plot(bincenters, y, 'r--', linewidth=1) plt.show()
def plot_z(self,figsize=(15,5)): import matplotlib.pyplot as plt import seaborn as sns if hasattr(self, 'sample'): sns.distplot(self.prior.transform(self.sample), rug=False, hist=False,label=self.method + ' estimate of ' + self.name) elif hasattr(self, 'value') and hasattr(self, 'std'): x = np.linspace(self.value-self.std*3.5,self.value+self.std*3.5,100) plt.figure(figsize=figsize) if self.prior.transform_name is None: plt.plot(x,mlab.normpdf(x,self.value,self.std),label=self.method + ' estimate of ' + self.name) else: sims = self.prior.transform(np.random.normal(self.value,self.std,100000)) sns.distplot(sims, rug=False, hist=False,label=self.method + ' estimate of ' + self.name) plt.xlabel('Value') plt.legend() plt.show() else: raise ValueError("No information on latent variable to plot!")
def plot_las(data, num_bins=100, color='red', xlabel=None, ylabel=None, title=None): """ plot_las(...) plot_las(data, num_bins=100, color='red', xlabel=None, ylabel=None, title=None) Plot a histogram with a normal distribution curve based on the data mean and standard deviation. Parameters ---------- data: numpy_array Numpy array with the variable to be assessed. num_bins : integer Number of bins in the histogram. Default = 100. color: string. Color of the bins. xlabel : string. Title of the X axis. Default = None. ylabel : string. Title of the Y axis. Default = None. title : string. Title of the histogram. Default = None. Notes ----- If xlabel, ylabel and title are not provided, the histogram will be plotted normally, however, without any of those elements. """ num_bins = num_bins fig, ax = plt.subplots() mu = np.mean(data) sigma = np.std(data) # Creates the histogram n, bins, patches = ax.hist(data, num_bins, color=color, histtype='stepfilled', normed=True) # add a 'best fit' line k = normpdf(bins, mu, sigma) ax.plot(bins, k, 'k--', linewidth=2) if xlabel != ylabel != title != None: ax.set_xlabel(xlabel, fontsize=16) ax.set_ylabel(ylabel, fontsize=16) ax.set_title(title) plt.ylim(0.0,0.15) plt.tick_params(axis='both', which='major', labelsize=16) plt.grid() plt.show()