我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.axhline()。
def saveFig(realDtb, fakeDtb, discriminator, outDir): axes = plt.gca() axes.set_xlim([-1,10]) axes.set_ylim([0,0.6]) axes.set_autoscale_on(False) plt.axhline(y = discriminator) plt.plot() real_mean = np.mean(realDtb) real_std = np.std(realDtb) real_pdf = norm.pdf(realDtb, real_mean, real_std) plt.plot(realDtb, real_pdf) fake_mean = np.mean(fakeDtb) fake_std = np.std(fakeDtb) fake_pdf = norm.pdf(fakeDtb, fake_mean, fake_std) plt.plot(fakeDtb, fake_pdf) plt.savefig(outDir)
def view(realDtb, fakeDtb, discriminator, outDir): plt.clf() axes = plt.gca() axes.set_xlim([-1,10]) axes.set_ylim([0,0.6]) axes.set_autoscale_on(False) plt.axhline(y = discriminator) plt.plot() real_mean = np.mean(realDtb) real_std = np.std(realDtb) real_pdf = norm.pdf(realDtb, real_mean, real_std) plt.plot(realDtb, real_pdf) fake_mean = np.mean(fakeDtb) fake_std = np.std(fakeDtb) fake_pdf = norm.pdf(fakeDtb, fake_mean, fake_std) plt.plot(fakeDtb, fake_pdf) plt.pause(0.00001)
def SimilarityPlot(self, SpectralDict): fig = plt.figure(figsize=(18,9)) # Add each data set to the Spectral Qualithy Plot for n, data_set in enumerate(SpectralDict['data_sets']): plt.scatter(SpectralDict['x_data'][n], SpectralDict['y_data'][n], color=self.color_codes[n], label=data_set) # Horizontal 800 Similarity line plt.axhline(y=800, xmin=0, xmax=1, hold=None, color=self.red_hex_code, label='800 Similarity') # Make your plot pretty plt.legend(loc='upper left') plt.ylabel('Similarity vs. Main NIST Hit') plt.xlabel('Concentration (pg)') plt.title('%s - Spectral Quality' % SpectralDict['analyte_name']) plt.xscale('log') plt.xlim(SpectralDict['x_axis_min'], SpectralDict['x_axis_max']) plt.savefig(SpectralDict['file_name'], bbox_inches='tight')
def plot_MNIST_results(): matplotlib.rcParams.update({'font.size': 10}) fig = plt.figure(figsize=(6,4), dpi=100) ll_1hl = [-92.17,-90.69,-89.86,-89.16,-88.61,-88.25,-87.95,-87.71] ll_2hl = [-89.17, -87.96, -87.10, -86.41, -85.96, -85.60, -85.28, -85.10] x = np.arange(len(ll_1hl)) plt.axhline(y=-84.55, color="black", linestyle="--", label="2hl-DBN") plt.axhline(y=-86.34, color="black", linestyle="-.", label="RBM") plt.axhline(y=-88.33, color="black", linestyle=":", label="NADE (fixed order)") plt.plot(ll_1hl, "r^-", label="1hl-NADE") plt.plot(ll_2hl, "go-", label="2hl-NADE") plt.xticks(x, 2**x) plt.xlabel("Models averaged") plt.ylabel("Test loglikelihood (nats)") plt.legend(loc=4, prop = {"size":10}) plt.subplots_adjust(left=0.12, right=0.95, top=0.97, bottom=0.10) plt.savefig(os.path.join(DESTINATION_PATH, "likelihoodvsorderings.pdf"))
def plot_bars_two_groups(group1, group2, groups, labels, title, fignum, filename): assert len(group1) == len(group2) and len(group2) == len(labels), 'incompatible arguments in plot_bars_two_groups' plt.figure(fignum) ind = np.arange(len(labels)) width = 1.0 rects1 = plt.bar(ind, group1, width, color='r', hatch='/', label=groups[0]) rects2 = plt.bar(ind+len(labels)+width, group2, width, color='y', hatch='\\', label=groups[1]) plt.ylabel('Change in Accuracy or BLEU', size='large', fontweight='demibold') plt.title(title, fontweight='demibold') ticks = np.concatenate((ind + width/2, len(labels) + ind + width + width/2)) #print ticks plt.xticks(ticks, labels + labels, size='large') plt.axhline(color='black') plt.legend() plt.tight_layout() #plt.show() plt.savefig(filename) #plot_bars_two_groups(word_diffs, char_diffs, ['Word', 'Char'], ['POS', 'Morph', 'BLEU'], 'Effect of Representation Layer', 3, 'layer-effect.png')
def plot_fps_vs_activity(s,W,brec): fig = plt.figure(figsize=(4,8)) for ii in range(5): plt.subplot(5,1,ii+1) Weff = W*(s[-1,ii,:]>0) fp = np.linalg.inv(np.eye(s.shape[2])-Weff).dot(brec) max_real = np.max(np.linalg.eig(Weff-np.eye(s.shape[2]))[0].real) plt.plot(s[60:,ii,:].T,c='c',alpha=.05) if max_real<0: plt.plot(fp,'k--') else: plt.plot(fp,'r--') plt.axhline(0,c='k') return fig
def main(win_stats, epsilon_start, min_epsilon, epsilon_episodes, count): epsilons = np.linspace(epsilon_start, min_epsilon, epsilon_episodes + 1) win_stat_count = win_stats.shape[0] epsilon_count = epsilons.shape[0] if epsilon_count < win_stat_count: epsilons = np.append(epsilons, np.full(win_stat_count - epsilon_count, min_epsilon)) win_stat_means = np.mean(win_stats.reshape(-1, count), axis=1) epsilon_means = np.mean(epsilons.reshape(-1, count), axis=1) episodes = np.arange(count, win_stat_count + 1, count) plt.plot(episodes, win_stat_means) plt.plot(episodes, epsilon_means) plt.axhline(0.5, alpha=0.7, linestyle='dotted', color='grey') plt.legend(['Win rate', r'$\epsilon$', '50 %']) plt.xlabel('Episodes') plt.ylabel('Means of wins over ' + str(count) + r' episodes each and $\epsilon$ values') plt.title('Win rate during learning') plt.savefig(file_name + '.png', bbox_inches='tight') plt.savefig(file_name + '.pdf', bbox_inches='tight') # plt.show()
def plot_2D_contour(states,p,labels,inter=False): import pylab as pl from pyme.statistics import expectation as EXP exp = EXP((states,p)) X = np.unique(states[0,:]) Y = np.unique(states[1,:]) X_len = len(X) Y_len = len(Y) Z = np.zeros((X.max()+1,Y.max()+1)) for i in range(len(p)): Z[states[0,i],states[1,i]] = p[i] Z = np.where(Z < 1e-8,0.0,Z) pl.clf() XX, YY = np.meshgrid(X,Y) pl.contour(range(X.max()+1),range(Y.max()+1),Z.T) pl.axhline(y=exp[1]) pl.axvline(x=exp[0]) pl.xlabel(labels[0]) pl.ylabel(labels[1]) if inter == True: pl.draw() else: pl.show()
def plot_note_dist(mat, name="", show_octaves=True): f = plt.figure(figsize=(20,5)) f.canvas.set_window_title(name) plt.imshow(mat.T, origin="lower", interpolation="nearest", cmap=my_cmap) plt.xticks( np.arange(0,4*(constants.WHOLE//constants.RESOLUTION_SCALAR),(constants.QUARTER//constants.RESOLUTION_SCALAR)) ) plt.xlabel('Time (beat/12)') plt.ylabel('Note') plt.colorbar() if show_octaves: for y in range(0,36,12): plt.axhline(y + 1.5, color='c') for x in range(0,4*(constants.WHOLE//constants.RESOLUTION_SCALAR),(constants.QUARTER//constants.RESOLUTION_SCALAR)): plt.axvline(x-0.5, color='k') for x in range(0,4*(constants.WHOLE//constants.RESOLUTION_SCALAR),(constants.WHOLE//constants.RESOLUTION_SCALAR)): plt.axvline(x-0.5, color='c') plt.show()
def axvlines(xs, **plot_kwargs): """ Draw vertical lines on plot :param xs: A scalar, list, or 1D array of horizontal offsets :param plot_kwargs: Keyword arguments to be passed to plot :return: The plot object corresponding to the lines. """ xs = np.array((xs, ) if np.isscalar(xs) else xs, copy=False) lims = plt.gca().get_ylim() x_points = np.repeat(xs[:, None], repeats=3, axis=1).flatten() y_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(xs), axis=0).flatten() plot = plt.plot(x_points, y_points, scaley = False, **plot_kwargs) return plot # return [plt.axhline(y, **specs) for y in ys] # return [plt.axvline(x, **specs) for x in xs]
def graph_winrates(winrates, color, outp_fn): import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt X = [] Y = [] for move_num in sorted(winrates.keys()): pl, wr = winrates[move_num] if pl != color: wr = 1. - wr X.append(move_num) Y.append(wr) plt.figure(1) plt.axhline(0.5, 0, max(winrates.keys()), linestyle='--', color='0.7') plt.plot(X, Y, color='k', marker='+') plt.xlim(0, max(winrates.keys())) plt.ylim(0, 1) plt.xlabel("Move Number", fontsize=28) plt.ylabel("Win Rate", fontsize=28) plt.savefig(outp_fn, dpi=200, format='pdf', bbox_inches='tight') #Also returns the move played, if any, else None
def vykresli_spojnice(hodnoty, nadpis, jednotky): fig, ax = pyplot.subplots() pyplot.title(nadpis) pyplot.xlabel('datum') pyplot.ylabel(jednotky) x_hodnoty = [polozka[0] for polozka in hodnoty] y_hodnoty = [polozka[1] for polozka in hodnoty] pyplot.plot_date(x_hodnoty, y_hodnoty, 'b-', linewidth=0.5) pyplot.axhline(0, linewidth=0.2) # v jakých intervalech a jak mají vypadat popisky na ose X ax.xaxis.set_major_locator(YearLocator()) pyplot.show()
def plot_res(test_err, train_batch_loss, benchmark_err, epoch): flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"] test_x_val = np.array(list(x * 3 for x in range(0, len(test_err)))) plt.plot(train_batch_loss[0],train_batch_loss[1], label="Training error", c=flatui[1], alpha=0.5) plt.plot(test_x_val, np.array(test_err), label="Test error", c=flatui[0]) plt.axhline(y=benchmark_err[1], linestyle='dashed', label="No-modell error", c=flatui[2]) plt.axhline(y=0.098, linestyle='dashed', label="State of the art error", c=flatui[3]) plt.suptitle("Model error - cold queries") plt.yscale('log', nonposy='clip') plt.xlim([0,epoch+1]) # second_axes = plt.twinx() # create the second axes, sharing x-axis # second_axes.set_yticks([0.2,0.4]) # list of your y values plt.xlabel('epoch') plt.ylabel('error') plt.legend(loc='upper right') plt.show()
def display_convw2(w, s, r, c, fig, title='conv_filters'): """w: num_filters X sizeX**2 * num_colors.""" num_f, num_d = w.shape assert s**2 * 3 == num_d pvh = np.zeros((s*r, s*c, 3)) for i in range(r): for j in range(c): pvh[i*s:(i+1)*s, j*s:(j+1)*s, :] = w[i*c + j, :].reshape(3, s, s).T mx = pvh.max() mn = pvh.min() pvh = 255*(pvh - mn) / (mx-mn) pvh = pvh.astype('uint8') plt.figure(fig) plt.suptitle(title) plt.imshow(pvh, interpolation="nearest") scale = 1 xmax = s * c ymax = s * r color = 'k' for x in range(0, c): plt.axvline(x=x*s/scale, ymin=0, ymax=ymax/scale, color=color) for y in range(0, r): plt.axhline(y=y*s/scale, xmin=0, xmax=xmax/scale, color=color) plt.draw() return pvh
def plot_pareto(coefficients, standard_errors, residual_df, alpha = 0.05): """Draws a pareto plot to the current pyplot figure.""" effects = [] for i, _ in enumerate(coefficients): effects.append(coefficients[i] / standard_errors[i]) pp.title("Pareto Chart") pp.xlabel("Rank") pp.ylabel("t-Value of |Effect|") bonferroni_limit = t.ppf(1 - ((alpha / 2) / 7), residual_df) t_limit = t.ppf(1 - (alpha / 2), residual_df) pp.axhline(y=t_limit, color='b', label="t-Value limit {:0.4f}".format(t_limit)) pp.axhline(y=bonferroni_limit, color='r', label="Bonferroni Limit {:0.4f}".format(bonferroni_limit)) heights = [] bar_colors = [] for t_value in effects: heights.append(abs(t_value)) if t_value >= 0: bar_colors.append('orange') else: bar_colors.append('b') # sort on |t-value| heights, bar_colors = (list(x) for x in zip(*sorted(zip(heights, bar_colors), key=lambda pair: pair[0], reverse=True))) # alternatively, could use numpy.argsort to get list of indices # indices = np.argsort(heights)[::-1] x_rank = np.arange(len(heights)) width = 0.35 bars = pp.bar(x_rank + width, heights, width, color=bar_colors) pp.gca().set_xticks(x_rank + (width * 1.5)) pp.gca().set_xticklabels([str(i + 1) for i in x_rank]) pp.gca().set_ylim([0, pp.gca().get_ylim()[1] * 1.1]) # expand the y max a bit so you can see the bonferroni line pp.legend() return bars
def plot_pull(data, func): import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator ax, bx = make_split(0.8) plt.sca(ax) x, y, norm = histpoints(data) lower, upper = ax.get_xlim() xs = np.linspace(lower, upper, 200) plt.plot(xs, norm * func(xs), 'b-') #plt.gca().yaxis.set_major_locator(MaxNLocator(prune='lower')) plt.sca(bx) resid = y[1] - norm * func(x) err = np.zeros_like(resid) err[resid >= 0] = y[0][resid >= 0] err[resid < 0] = y[2][resid < 0] pull = resid / err plt.errorbar(x, pull, yerr=1, color='k', fmt='o') plt.ylim(-5, 5) plt.axhline(0, color='b') plt.sca(ax) return ax, bx
def visualize_document_topics_heatmap(self, outfile, set_topics=False): self.sort_doctopics_groups() doctopics_raw_hm = numpy.rot90(self.document_topics_raw) rows, columns = doctopics_raw_hm.shape rownames = self.topic_labels columnnames = self.document_names pyplot.pcolor(doctopics_raw_hm, norm=None, cmap='Blues') pyplot.gca().invert_yaxis() if self.group_names: ticks_groups = [] bounds = [] current_group = False start = 0 for i,doc in enumerate(self.document_names): group = self.document_group_dict[doc] if group != current_group: if i != 0: bounds.append(i-1) ticks_groups[start+int((i-start)/2)] = current_group current_group = group start=i ticks_groups.append('') ticks_groups[start+int((i-start)/2)] = current_group pyplot.xticks(numpy.arange(columns)+0.5,ticks_groups, fontsize=11) if set_topics: for index in set_topics: pyplot.axhline(y=index) topic_names = self.return_topic_names(set_topics) pyplot.yticks(set_topics,topic_names,fontsize=8) else: pyplot.yticks(numpy.arange(rows)+0.5, rownames, fontsize=8) for bound in bounds: pyplot.axvline(x=bound) pyplot.colorbar(cmap='Blues') pyplot.savefig(outfile) pyplot.clf()
def plot_grid(): plt.axvline(x=0, color="#999999", linestyle="-") plt.axhline(y=0, color="#999999", linestyle="-")
def plot_1Dgrid(z, grids): totalgrid = list(set(reduce(lambda a, b: a+b, grids)) - set(z)) fig = plt.figure("line") fig.set_size_inches(8, 1) plt.axhline(y=0, color="black", zorder=-10) plt.scatter(totalgrid, [0.]*len(totalgrid), color="black") plt.scatter(z, [0.]*len(z), color="red") plt.xlim(z[0]-1, z[-1]+1) plt.axis('off')
def acf_plot(data, max_lag=10): import matplotlib.pyplot as plt import seaborn as sns plt.figure(figsize=(15,5)) ax = plt.subplot(111) plt.bar(range(1,10), [acf(data,lag) for lag in range(1,10)]) plt.xlabel("Lag") plt.ylabel("Autocorrelation") plt.title("ACF Plot") plt.axhline(0+2/np.sqrt(len(data)), linestyle="-", color="black") plt.axhline(0-2/np.sqrt(len(data)), linestyle="-", color="black") plt.show()
def weibull_contour(Y, U, is_discrete, true_alpha, true_beta, logx=True, samples=200, lines=True): xlist = np.linspace(true_alpha / np.e, true_alpha * np.e, samples) ylist = np.linspace(true_beta / np.e, true_beta * np.e, samples) x_grid, y_grid = np.meshgrid(xlist, ylist) loglik = x_grid * 0 if is_discrete: fun = weibull.discrete_loglik else: fun = weibull.continuous_loglik for i in xrange(len(Y)): loglik = loglik + \ fun(Y[i], x_grid, y_grid, U[i]) z_grid = loglik / len(Y) plt.figure() if logx: x_grid = np.log(x_grid) true_alpha = np.log(true_alpha) xlab = r'$\log(\alpha)$' else: xlab = r'$\alpha$' cp = plt.contourf(x_grid, y_grid, z_grid, 100, cmap='jet') plt.colorbar(cp) if lines: plt.axvline(true_alpha, linestyle='dashed', c='black') plt.axhline(true_beta, linestyle='dashed', c='black') plt.xlabel(xlab) plt.ylabel(r'$\beta$')
def plot_model_comparison(self,redshift,dv,central_wave=None): """ Plot best fit model onto spectrum for visual inspection """ c = 299792.485 # [km/s] if central_wave == None: # Use the first transition as the central wavelength central_wave = self.config_param.transitions_params_array[0][0][0][1] else: central_wave = float(central_wave) obs_spec_wave = self.config_param.wave / (1+redshift) obs_spec_dv = c*(obs_spec_wave - central_wave) / central_wave plt.rc('text', usetex=True) plt.figure(1) plt.step(obs_spec_dv,self.config_param.flux,'k',label=r'$\rm Data$') plt.step(obs_spec_dv,self.model_flux,'b',lw=2,label=r'$\rm Best\,Fit$') plt.step(obs_spec_dv,self.config_param.dflux,'r') plt.axhline(1,ls='--',c='g',lw=1.2) plt.axhline(0,ls='--',c='g',lw=1.2) plt.ylim([-0.1,1.4]) plt.xlim([-dv,dv]) plt.xlabel(r'$dv\,[\rm km/s]$') plt.ylabel(r'$\rm Normalized\,Flux$') plt.legend(loc=3) output_name = self.config_param.processed_product_path + '/modelspec_' + self.config_param.chain_short_fname + '.pdf' plt.savefig(output_name,bbox_inches='tight',dpi=100) plt.clf() print('Written %s' % output_name)
def model_fit_and_test(TrainX,TrainY,TestX,TestY): def bulid_model(model_name): model = model_name() return model #for model_name in [LinearRegression, Ridge, Lasso, ElasticNet, KNeighborsRegressor, DecisionTreeRegressor, SVR,RandomForestRegressor, AdaBoostRegressor, GradientBoostingRegressor]: for model_name in [LinearRegression, ElasticNet]: model = bulid_model(model_name) model.fit(TrainX,TrainY) print(model_name) resid = model.predict(TestX) - TestY #print resid print("Residual sum of squares: %f"% np.mean(resid ** 2)) #print model.predict(TestX) #print TestY # Explained variance score: 1 is perfect prediction plt.scatter(model.predict(TestX), resid); plt.axhline(0, color='red') plt.xlabel('Predicted Values') plt.ylabel('Residuals') #plt.xlim([1, 50]) plt.show() print('Variance score: %.2f' % model.score(TestX, TestY)) from statsmodels.stats.stattools import jarque_bera _, pvalue, _, _ = jarque_bera(resid) print ("Test Residuals Normal", pvalue) from statsmodels import regression, stats import statsmodels.api as sms import statsmodels.stats.diagnostic as smd # xs_with_constant = sms.add_constant(np.column_stack((X1,X2,X3,X4))) xs_with_constant = sms.add_constant(TestX) _, pvalue1, _, _ = stats.diagnostic.het_breushpagan(resid, xs_with_constant) print ("Test Heteroskedasticity", pvalue1) ljung_box = smd.acorr_ljungbox(resid, lags=10) #print "Lagrange Multiplier Statistics:", ljung_box[0] print "Test Autocorrelation P-values:", ljung_box[1] if any(ljung_box[1] < 0.05): print "The residuals are autocorrelated." else: print "The residuals are not autocorrelated."
def plot_error_rate(er_train, er_test): df_error = pd.DataFrame([er_train, er_test]).T df_error.columns = ['Training', 'Test'] plot1 = df_error.plot(linewidth = 3, figsize = (8,6), color = ['lightblue', 'darkblue'], grid = True) plot1.set_xlabel('Number of iterations', fontsize = 12) plot1.set_xticklabels(range(0,450,50)) plot1.set_ylabel('Error rate', fontsize = 12) plot1.set_title('Error rate vs number of iterations', fontsize = 16) plt.axhline(y=er_test[0], linewidth=1, color = 'red', ls = 'dashed')
def main(durak_stats, epsilon_start, min_epsilon, epsilon_episodes, count): epsilons = np.linspace(epsilon_start, min_epsilon, epsilon_episodes + 1) durak_stat_count = durak_stats.shape[0] epsilon_count = epsilons.shape[0] if epsilon_count < durak_stat_count: epsilons = np.append(epsilons, np.full(durak_stat_count - epsilon_count, min_epsilon)) ix_count = max(durak_stats) + 1 durak_stat_means_list = [] for ix in range(ix_count): durak_stat_means = np.ones(durak_stat_count, dtype=np.float) durak_stat_means[np.where(durak_stats == ix)] = 0 durak_stat_means_list.append( np.mean(durak_stat_means.reshape(-1, count), axis=1)) epsilon_means = np.mean(epsilons.reshape(-1, count), axis=1) episodes = np.arange(count, durak_stat_count + 1, count) win_rate_strings = [] for ix in range(ix_count): plt.plot(episodes, durak_stat_means_list[ix]) win_rate_strings.append('Win rate for player {0}'.format(ix)) plt.plot(episodes, epsilon_means) plt.axhline(0.5, alpha=0.7, linestyle='dotted', color='grey') plt.legend(win_rate_strings + [r'$\epsilon$', '50 %']) plt.xlabel('Episodes') plt.ylabel('Means of wins over ' + str(count) + r' episodes each and $\epsilon$ values') plt.title('Win rate during learning') plt.savefig(file_name + '.png', bbox_inches='tight') plt.savefig(file_name + '.pdf', bbox_inches='tight') # plt.show()
def runsimplot(self): """ Viz of the MC results """ tdmin = self.iniest.td - 3.0*self.iniest.tderr tdmax = self.iniest.td + 3.0*self.iniest.tderr fig = plt.figure(figsize=(6, 3)) fig.subplots_adjust(top=0.95, bottom=0.2) plt.scatter(self.simtruedelays, self.simmesdelays - self.simtruedelays) plt.xlim(tdmin, tdmax) plt.xlabel("True delay [day]") plt.ylabel("Measurement error [day]") plt.axvline(self.iniest.td - self.iniest.tderr, color="gray", linestyle="-", zorder=20) plt.axvline(self.iniest.td + self.iniest.tderr, color="gray", linestyle="-", zorder=20) plt.axhline(0, color="black", linestyle="-", zorder=20) plt.axhline(- self.iniest.tderr, color="gray", linestyle="-", zorder=20) plt.axhline(+ self.iniest.tderr, color="gray", linestyle="-", zorder=20) plt.axhspan(-self.outest.tderr, self.outest.tderr, xmin=0, xmax=1, lw=0, color="red", alpha=0.2) #plt.ylim(- 2.0*self.iniest.tderr, + 2.0*self.iniest.tderr) plt.figtext(0.15, 0.8, "Total/initial error ratio: %.2f" % self.totalratio) #ax = plt.gca() #plt.figtext(0.15, 0.8, "Intrinsic/initial error ratio: %.2f" % self.intrinsicratio) #plt.axvline(self.iniest.td - self.iniest.tderr, color="gray", linestyle="-", zorder=20) #plt.axvline(self.iniest.td + self.iniest.tderr, color="gray", linestyle="-", zorder=20) #plt.axvline(self.outest.td, color="red", linestyle="-", zorder=20) plt.savefig(os.path.join(self.plotdir, "measvstrue.png")) plt.close()
def maxPplot(estslist, N, filepath=None): """ Give me a list of estimate-lists, I plot P as a function of f N is the total number of curves (e.g. 56 for tdc0) (defines f=1) """ for ests in estslist: estscp = ests[:] # Important, we work on a copy, do not modify the original ! for e in estscp: if e.td == 0.0: # We want to avoid that... #print e e.td = 0.1 ests = sortbyP(estscp) fs = [] Ps = [] for n in range(len(ests)): subests = ests[n:] fs.append(f(subests, N)) Ps.append(P(subests)) plt.plot(fs, Ps, ".-", label=ests[0].method) plt.xlabel("f") plt.ylabel("Approximation of P") plt.xlim(0.0, 0.8) plt.ylim(0.0, 0.8) plt.axvline(0.3, color="black") plt.axhline(0.15, color="black") if len(estslist) > 1: plt.legend() plt.grid() if filepath: plt.savefig(filepath) else: plt.show() ############## Here, we work with the database from analyse_results ##############
def _plot_tracks(tracks): colors = ['r', 'b'] n_tracks = min({len(tracks.columns), len(colors)}) for i in range(n_tracks): ob = tracks.iloc[:, i].values plt.plot(tracks.index, ob, colors[i], lw=0.5) plt.ylim(((1.1 if min(ob) < 0 else -1.1) * min(ob), 1.1 * max(ob))) if min(ob) < 0 < max(ob): plt.axhline(y=0.0, color='k', lw=0.5)
def bubble(data,x,y,hue,bsize,palette='Reds',xscale='linear',yscale='linear',title='',suptitle=0): if suptitle == 0: suptitle = bsize sns.set(style="whitegrid") sns.set_context("notebook", font_scale=3, rc={"lines.linewidth": 0.3}) sns.set_color_codes("bright") size = (1500 / float(data[bsize].max())) size = data[bsize] * size g = sns.PairGrid(data, hue=hue, palette=palette, y_vars=y, x_vars=x, size=12, aspect=3) g.map(plt.scatter, s=size); g.set(xscale=xscale) g.set(yscale=yscale) g.add_legend(title=hue, bbox_to_anchor=(0.9, 0.6)) plt.title(title, fontsize=48, y=1.12, color="gray"); plt.suptitle("size = " + suptitle, verticalalignment='top', fontsize=35, y=1.01, x=0.48, color="gray") plt.xlabel(x, fontsize=38, labelpad=30, color="gray"); plt.ylabel(y, fontsize=38, labelpad=30, color="gray"); plt.tick_params(axis='both', which='major', pad=25) plt.axhline(linewidth=2.5, color="black"); plt.axvline(linewidth=2.5, color="black"); plt.ylim(0,); plt.xlim(0,);
def work_with_activation_functions(): X = np.array([[1, 1.4, 1.5]]) w = np.array([0.0, 0.2, 0.4]) print("P(y=1|x) = %.3f\n" % logistic_activation(X, w)[0]) W = np.array([[1.1, 1.2, 1.3, 0.5], [0.1, 0.2, 0.4, 0.1], [0.2, 0.5, 2.1, 1.9]]) A = np.array([[1.0], [0.1], [0.3], [0.7]]) Z = W.dot(A) y_probas = logistic(Z) print('Probabilities:\n', y_probas) y_class = np.argmax(Z, axis=0) print("Predicted class label: %d\n" % y_class[0]) y_probas = softmax(Z) print('Probabilities:\n', y_probas) print("Sum: %s" % y_probas.sum()) y_class = np.argmax(Z, axis=0) print("Predicted class label: %d" % y_class[0]) z = np.arange(-5, 5, 0.005) log_act = logistic(z) # scipy.special.expit(z) tanh_act = tanh(z) # numpy.tanh(z) plt.ylim([-1.5, 1.5]) plt.xlabel('net input $z$') plt.ylabel('activation $\phi(z)$') plt.axhline(1, color='black', linestyle='--') plt.axhline(0.5, color='black', linestyle='--') plt.axhline(0, color='black', linestyle='--') plt.axhline(-1, color='black', linestyle='--') plt.plot(z, tanh_act, linewidth=2, color='black', label='tanh') plt.plot(z, log_act, linewidth=2, color='lightgreen', label='logistic') plt.legend(loc='lower right') plt.show()
def plot_regularization_path(columns, X, y): fig = plt.figure() ax = plt.subplot(111) colors = [ 'blue', 'green', 'red', 'cyan', 'magenta', 'yellow', 'black', 'pink', 'lightgreen', 'lightblue', 'gray', 'indigo', 'orange', ] weights = [] params = [] for c in np.arange(-4, 6): lr = LogisticRegression(penalty='l1', C=10**c, random_state=0) lr.fit(X, y) weights.append(lr.coef_[1]) params.append(10**c) weights = np.array(weights) for column, color in zip(range(weights.shape[1]), colors): plt.plot( params, weights[:, column], label=columns[column+1], color=color, ) plt.axhline(0, color='black', linestyle='--', linewidth=3) plt.xlim([10**-5, 10**5]) plt.ylabel('weight coefficient') plt.xlabel('C') plt.xscale('log') plt.legend(loc='upper left') ax.legend( loc='upper center', bbox_to_anchor=(1.38, 1.03), ncol=1, fancybox=True, ) plt.show()
def survivalFreq(X='Age',diff=False): groupS = df.groupby(['Survived']).get_group(1) groupS = groupS.groupby([X])[X].aggregate(len) groupS = pd.DataFrame({X: groupS.index, 'Frequency': groupS.values}) groupD = df.groupby(['Survived']).get_group(0) groupD = groupD.groupby([X])[X].aggregate(len) groupD = pd.DataFrame({X: groupD.index, 'Frequency': groupD.values}) group = pd.merge(groupD, groupS, how='inner', on=X, suffixes=('Dead', 'Survived')) if not diff: group[['FrequencyDead', 'FrequencySurvived']].plot.bar(x=group[X], title='%s And Survival Frequency'%X, stacked=True) else: group['diff'] = group.FrequencySurvived - group.FrequencyDead group[['diff']].plot.bar(x=group[X], title='%s And Survival Frequency'%X, stacked=True); plt.axhline(0, color='k')
def _plot_timeseries(ax, ch_idx, tmin, tmax, vmin, vmax, ylim, data, color, times, vline=None, x_label=None, y_label=None, colorbar=False, hline=None): """Aux function to show time series on topo split across multiple axes""" import matplotlib.pyplot as plt picker_flag = False for data_, color_ in zip(data, color): if not picker_flag: # use large tol for picker so we can click anywhere in the axes ax.plot(times, data_[ch_idx], color_, picker=1e9) picker_flag = True else: ax.plot(times, data_[ch_idx], color_) if vline: for x in vline: plt.axvline(x, color='w', linewidth=0.5) if hline: for y in hline: plt.axhline(y, color='w', linewidth=0.5) if x_label is not None: plt.xlabel(x_label) if y_label is not None: if isinstance(y_label, list): plt.ylabel(y_label[ch_idx]) else: plt.ylabel(y_label) if colorbar: plt.colorbar()
def plot_spatiotemporal(B,Bs,Bh,ch_map): ''' Q = plot_spatiotemporal(B,Bs,Bh,ch_map) Decompress and visualize spatiotemporal stimulus model Parameters ---------- B : nspace * nhist spatiotemporal parameter vector, compressed Bs : nspace × channels spatial compression basis Bh : nhist × hframes history compression basis ch_map : 2d array showing how to map stimulus indecies into a space Returns ------- Q : the ch_map.shape × hframes decompressed spatiotemporal history filter ''' nspace,nchannels = Bs.shape nhist ,hframes = Bh.shape assert(nspace<=nchannels) assert(nhist<=hframes) assert(B.shape==(nspace*nhist,)) # decompress stimulus and place into channel map Q = np.linalg.pinv(Bs).real.dot(B.reshape((nspace,nhist))).dot(np.linalg.pinv(Bh).real.T)[ch_map,:] # plot # Truncate time history to a perfect square, and reshape data K = int(np.sqrt(Q.shape[-1])) Q2 = Q.transpose((2,0,1))[:K*K,...].reshape((K,K)+(ch_map.shape)) # Form grid depiction of spatiotmeporal history Q2 = np.concatenate(np.concatenate(Q2,axis=1),axis=1) # plot z-scores zscores = (Q2-np.mean(Q2))/np.std(Q2) plt.imshow(zscores,vmin=-8,vmax=8) # draw a better grid plt.gca().grid(False) for i in range(K): plt.axvline(i*ch_map.shape[0],color=(0.1,)*3) plt.axhline(i*ch_map.shape[1],color=(0.1,)*3) return Q
def draw_correct_line(): ''' ?????sin??? ''' x = np.arange(0, 2 * np.pi, 0.01) x = x.reshape((len(x), 1)) y = np.sin(x) pylab.plot(x,y, label = '??sin??') plt.axhline(linewidth=1, color='r')
def plot_speedup_acc(speedup_acc, score1): num_procs = speedup_acc[0].shape[0] plt.figure(figsize=(15, 3)) plt.subplot(1, 3, 1) plt.plot(range(1,num_procs+1), speedup_acc[0]) plt.axhline(1, c='r') plt.xlabel("Processors") plt.xticks(range(1,num_procs+1)) plt.ylabel("Speed-up") plt.yticks(np.arange(0,num_procs+1, 0.5)) plt.subplot(1, 3, 2) plt.plot(range(1,num_procs+1), speedup_acc[1]) plt.axhline(y=score1, c='r') plt.xlabel("Processors") plt.xticks(range(1,num_procs+1)) plt.ylabel("Accuracy") plt.yticks(np.arange(0,1.25, 0.25)) plt.subplot(1, 3, 3) plt.scatter(speedup_acc[0], speedup_acc[1]) plt.xlabel("Speed-up") plt.xticks(np.arange(0,num_procs+1, 0.5)) plt.ylabel("Accuracy") plt.yticks(np.arange(0,1.25, 0.25))
def plot_res(test_err, train_batch_loss, benchmark_err, epoch): '''Plot result of model Args: test_err: 'float', test error of model train_batch_loss: 'tuple', tuple of train error of model x & y benchmark_err: 'tuple', error of using no model epoch: 'int', current epoch ''' flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"] test_x_val = np.array(list(x * 3 for x in range(0, len(test_err)))) plt.plot(train_batch_loss[0],train_batch_loss[1], label="Training error", c=flatui[1], alpha=0.5) plt.plot(test_x_val, np.array(test_err), label="Test error", c=flatui[0]) plt.axhline(y=benchmark_err[1], linestyle='dashed', label="No-modell error", c=flatui[2]) plt.axhline(y=0.098, linestyle='dashed', label="State of the art error", c=flatui[3]) plt.suptitle("Model error - cold queries") plt.yscale('log', nonposy='clip') plt.xlim([0,epoch+1]) plt.xlabel('epoch') plt.ylabel('error') plt.legend(loc='upper right') plt.show()
def plot(self,axs=None,ls="-",marker="None",xlim=[None,None],label="",**plotargs): if axs is None: fig, axs = plt.subplots(nrows=4,ncols=1,sharex=True) ax = axs[0] plt.sca(ax) plt.plot(self["RM"],self["P"],ls=ls,marker=marker,**plotargs) plt.ylabel("$P$ (Jy rad$^{-1}$ m$^{2}$)") plt.xlim(xlim) plt.ylim(0,) ymax = np.max(ax.get_ylim()) ax = axs[1] plt.sca(ax) chi = self["chi"] chi[self["P"] < np.max(self["P"]) * 0.01]=0 plt.plot(self["RM"],chi,ls=ls,marker=marker,**plotargs) plt.ylabel("$\chi$ (deg)") plt.xlim(xlim) plt.ylim(-90,90) ax.set_yticks(np.arange(-90,91,10), minor=True) ax.set_yticks(np.arange(-90,91,30), minor=False) ax = axs[2] plt.sca(ax) plt.plot(self["RM"],self["Q"],ls=ls,marker=marker,**plotargs) plt.axhline(0, ls="--", color="black") plt.ylabel("$Q$ (Jy rad$^{-1}$ m$^{2}$)") plt.xlim(xlim) plt.ylim(-ymax,ymax) # ax = axs[3] plt.sca(ax) plt.plot(self["RM"],self["U"],ls=ls,marker=marker,**plotargs) plt.axhline(0, ls="--", color="black") plt.ylabel("$U$ (Jy rad$^{-1}$ m$^{2}$)") plt.xlabel("$\phi$ (rad m$^{-2}$)") plt.xlim(xlim) plt.ylim(-ymax,ymax) return axs
def att_plot(top_labels, gt_ind, probs, fn): # plt.figure(figsize=(5, 5)) # # color_dict = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS) # colors = [color_dict[c] for c in # ['lightcoral', 'steelblue', 'forestgreen', 'darkviolet', 'sienna', 'dimgrey', # 'darkorange', 'gold']] # colors[gt_ind] = color_dict['crimson'] # w = 0.9 # plt.bar(np.arange(len(top_labels)), probs, w, color=colors, alpha=.9, label='data') # plt.axhline(0, color='black') # plt.ylim([0, 1]) # plt.xticks(np.arange(len(top_labels)), top_labels, fontsize=6) # plt.subplots_adjust(bottom=.15) # plt.tight_layout() # plt.savefig(fn) lab = deepcopy(top_labels) lab[gt_ind] += ' (gt)' d = pd.DataFrame(data={'probs': probs, 'labels':lab}) fig, ax = plt.subplots(figsize=(4,5)) ax.tick_params(labelsize=15) sns.barplot(y='labels', x='probs', ax=ax, data=d, orient='h', ci=None) ax.set(xlim=(0,1)) for rect, label in zip(ax.patches,lab): w = rect.get_width() ax.text(w+.02, rect.get_y() + rect.get_height()*4/5, label, ha='left', va='bottom', fontsize=25) # ax.yaxis.set_label_coords(0.5, 0.5) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.get_yaxis().set_visible(False) ax.get_xaxis().label.set_visible(False) fig.savefig(fn, bbox_inches='tight', transparent=True) plt.close('all')
def diagnostics(self, tmin=None, tmax=None, show=True): innovations = self.ml.innovations(tmin, tmax) fig = self._get_figure() gs = plt.GridSpec(2, 3, wspace=0.2) plt.subplot(gs[0, :2]) plt.title('Autocorrelation') # plt.axhline(0.2, '--') r = ps.stats.acf(innovations) plt.stem(r) plt.subplot(gs[1, :2]) plt.title('Partial Autocorrelation') # plt.axhline(0.2, '--') # plt.stem(self.ml.stats.pacf()) plt.subplot(gs[0, 2]) innovations.hist(bins=20) plt.subplot(gs[1, 2]) probplot(innovations, plot=plt) if show: plt.show() return fig.axes
def display_w(w, s, r, c, fig, vmax=None, vmin=None, dataset='mnist', title='weights'): if dataset == 'norb': numvis = 4096 else: numvis = w.shape[0] numhid = w.shape[1] sc = s sr = numvis/s if isinstance(w, np.ndarray): vh = w.T[:,:sr*sc].reshape(sr*numhid, sc) else: vh = w.asarray().T[:,:sr*sc].reshape(sr*numhid, sc) pvh = np.zeros((sr*r, sc*c)) for i in range(r): for j in range(c): pvh[i*sr:(i+1)*sr , j*sc:(j+1)*sc] = vh[ (i*c+j)*sr : (i*c+j+1)*sr ,:] plt.figure(fig) plt.clf() plt.title(title) plt.imshow(pvh, cmap = plt.cm.gray, interpolation = 'nearest', vmax=vmax, vmin=vmin) scale = 1 xmax = sc*c ymax = sr*r color = 'k' if r > 1: for x in range(0,c): plt.axvline(x=x*sc/scale, ymin=0,ymax=ymax/scale, color = color) if c > 1: for y in range(0,r): plt.axhline(y=y*sr/scale, xmin=0,xmax=xmax/scale, color = color) plt.draw() return pvh
def save_fig(self, epoch): plt.clf() real_A = Variable(torch.Tensor(np.reshape(self.data_A, (sample_size, 1)))) #100*1 matrix real_B = Variable(torch.Tensor(np.reshape(self.data_B, (sample_size, 1)))) #100*1 matrix fake_B = self.netG_A.forward(real_A) D_B_score = self.netD_A.forward(self.fake_B) lm = sns.distplot(np.array(self.extract(real_A)), hist=False, color="g", kde_kws={"shade": True}) lm = sns.distplot(np.array(self.extract(fake_B)), hist=False, color="m", kde_kws={"shade": True}) lm = sns.distplot(np.array(self.extract(real_B)), hist=False, color="b", kde_kws={"shade": True}) plt.axhline(np.average(np.array(self.extract(D_B_score)))) axes = lm.axes axes.set_xlim([-2,4]) axes.set_ylim([0,3]) outDir = "/Users/maureen/Documents/Python/simpleGAN/DomainB/shift/" + str(epoch) +".png" plt.savefig(outDir) plt.clf() real_A = Variable(torch.Tensor(np.reshape(self.data_A, (sample_size, 1)))) #100*1 matrix real_B = Variable(torch.Tensor(np.reshape(self.data_B, (sample_size, 1)))) #100*1 matrix fake_A = self.netG_B.forward(real_B) D_A_score = self.netD_B.forward(self.fake_A) lm = sns.distplot(np.array(self.extract(real_B)), hist=False, color="g", kde_kws={"shade": True}) lm = sns.distplot(np.array(self.extract(fake_A)), hist=False, color="m", kde_kws={"shade": True}) lm = sns.distplot(np.array(self.extract(real_A)), hist=False, color="b", kde_kws={"shade": True}) plt.axhline(np.average(np.array(self.extract(D_A_score)))) axes = lm.axes axes.set_xlim([-2, 4]) axes.set_ylim([0,3]) outDir = "/Users/maureen/Documents/Python/simpleGAN/DomainA/shift/" + str(epoch) +".png" plt.savefig(outDir) # real_B = Variable(b_sampler(data_size, 1)) #100*1 matrix # fake_A = self.netG_B.forward(real_B) # rec_B = self.netG_A.forward(fake_A) ####start to train cycle-GAN####
def plot(self,keys=None,burn=1000): if keys is None: keys=self.names0 k=0 #plm=putil.Plm1(rows=2,cols=2,xmulti=True,ymulti=True,slabel=False) for i in range(len(keys)): for j in range(len(keys)): k=k+1 if i==j: x=self.chain[keys[i]][burn:] plt.subplot(len(keys),len(keys),k) #sig=np.std(self.chain[keys[i]][burn:]) xmean=np.mean(x) nbins=np.max([20,x.size/1000]) plt.hist(x,bins=nbins,normed=True,histtype='step') plt.axvline(np.mean(self.chain[keys[i]][burn:]),lw=2.0,color='g') if i == (len(keys)-1): plt.xlabel(self.descr[keys[i]][3]) plt.text(0.05,0.7,stat_text(self.chain[keys[i]][burn:]),transform=plt.gca().transAxes) plt.gca().xaxis.set_major_locator(MaxNLocator(3, prune="both")) plt.gca().yaxis.set_major_locator(MaxNLocator(3, prune="both")) plt.gca().set_yticklabels([]) else: if i > j: plt.subplot(len(keys),len(keys),k) x=self.chain[keys[j]][burn:] y=self.chain[keys[i]][burn:] nbins=np.max([32,x.size/1000]) plt.hist2d(x,y,bins=[nbins,nbins],norm=LogNorm()) plt.axvline(np.mean(self.chain[keys[j]][burn:]),lw=2.0) plt.axhline(np.mean(self.chain[keys[i]][burn:]),lw=2.0) if j == 0: plt.ylabel(self.descr[keys[i]][3]) else: plt.gca().set_yticklabels([]) if i == (len(keys)-1): plt.xlabel(self.descr[keys[j]][3]) else: plt.gca().set_xticklabels([]) plt.gca().xaxis.set_major_locator(MaxNLocator(3, prune="both")) plt.gca().yaxis.set_major_locator(MaxNLocator(3, prune="both")) #plt.colorbar(pad=0.0,fraction=0.1) plt.subplots_adjust(hspace=0.15,wspace=0.1)
def plotline(dataset_name, yvalues, loc_legend=3, figure_name=None, axis=[0, 1010, 40, 100], classifiers=['HoeffdingTree'], drifts=None, gradual_drift=None, xvalues=[100, 200, 300, 400, 500, 600, 700, 800, 900, 1000], xlabel='# instances (thousands)', ylabel='accuracy'): plt.title(dataset_name + ' - ' + ylabel) plt.axis(axis) line_style = ['-o', '-x', '-p', '-1', '-s', '-v', '-d'] idx = 0 stream_classifier = [] for classifier in classifiers: plotted, = plt.plot(xvalues, yvalues[classifier], line_style[idx % len(line_style)], label=classifier) stream_classifier.append(plotted) idx+=1 plt.axhline(y=0, xmax=1, color='black', ls='--') if drifts is not None: for drift in drifts: if gradual_drift is not None: if isinstance(gradual_drift, types.ListType) is False: plt.axvline(x=drift-gradual_drift, ymax=1, color='r', ls='--') plt.axvline(x=drift+gradual_drift, ymax=1, color='r', ls='--') plt.axvline(x=drift, ymax=1, color='r') if isinstance(gradual_drift, types.ListType): for i in range(0,len(gradual_drift)): if gradual_drift[i] > 0: plt.axvline(x=drifts[i]-gradual_drift[i], ymax=1, color='r', ls='--') plt.axvline(x=drifts[i]+gradual_drift[i], ymax=1, color='r', ls='--') plt.legend(stream_classifier, classifiers, loc=loc_legend, ncol=2, bbox_to_anchor=(0., 0, 1, 0)) plt.ylabel(ylabel) plt.xlabel(xlabel) if figure_name is None: figure_name = 'plot.pdf' plt.savefig(figure_name) plt.clf()
def make_strat_image(info, data): mdpi = 300 try: title = "{0} on {1} {2} [{3}]".format(info["system"], info["symbol"], \ info["period"], info["broker"]) if len(data) > 0: data.rename(columns={'LONG_PL_CUMSUM': 'Strategy, longs', \ 'SHORT_PL_CUMSUM': 'Strategy, shorts', 'LONG_DIFF_CUMSUM': \ 'Buy & hold', 'SHORT_DIFF_CUMSUM': 'Short & hold'}, inplace=True) plt.figure(figsize=(3840/mdpi, 2160/mdpi), dpi=mdpi) data['Strategy, longs'].plot(x='Date', y='Value, $', legend=True, \ style='r', lw=3).scatter(x=data.index, \ y=data.LONG_MAE, label='MAE', color='DarkGreen') data['Buy & hold'].plot(legend=True, style='g').set_title(title+', Longs') plt.axhline(y=0.0) info["direction"] = "longs" plt.savefig(filename_constructor(info=info, folder="meta")) plt.close() plt.figure(figsize=(3840/mdpi, 2160/mdpi), dpi=mdpi) data['Strategy, shorts'].plot(x='Date', y='Value, $', legend=True, \ style='r', lw=3).scatter(x=data.index, \ y=data.SHORT_MAE, label='MAE', color='DarkGreen') data['Short & hold'].plot(legend=True, style='g').set_title(title+', Shorts') plt.axhline(y=0.0) info["direction"] = "shorts" plt.savefig(filename_constructor(info=info, folder="meta")) plt.close() plt.figure(figsize=(3840/mdpi, 2160/mdpi), dpi=mdpi) data['Strategy, longs & shorts'] = data['Strategy, shorts'] + \ data['Strategy, longs'] data['Strategy, longs & shorts'].plot(x='Date', \ y='Value, $', legend=True, style='r', \ lw=3).scatter(x=data.index, y=(data.SHORT_MAE+data.LONG_MAE), \ label='MAE', color='DarkGreen') data['Buy & hold'].plot(legend=True, style='g'\ ).set_title(title+', Longs & shorts') plt.axhline(y=0.0) info["direction"] = "longs_shorts" plt.savefig(filename_constructor(info=info, folder="meta")) plt.close() if settings.SHOW_DEBUG: print(colored.green("Made images")) except Exception as err: print(colored.red("At make_strat_image {}".format(err)))
def graph(self, order, coefficients, low, high, interval, ans): fig=plt.figure() plt.axes(xlim=(low-5, high+5)) lines = [plt.plot([], [], color='r')[0] for i in range(30)] plt.title('Trapezoid Method\nRequired area is %0.2f units' %(ans)) plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.axhline(y=0, color='k') plt.axvline(x=0, color='k') x=np.linspace(low, high, 500) y=f(order, coefficients, x) s='' for i in range(order+1): if coefficients[i]>=0: s=s+(' +'+str(coefficients[i])+'x^'+str(order-i)) else: s=s+(' '+str(coefficients[i])+'x^'+str(order-i)) s=s+' = 0' plt.plot(x, y, 'darkslateblue', label=s) def init(): for line in lines: line.set_data([], []) return lines def animate(i): if i<2: for j in range(30): lines[j].set_data([], []) else: x = np.linspace(low, high, i) y = f(order, coefficients, x) lines[29].set_data(x, y) for j in range(i): lines[j].set_data([x[j], x[j]], [y[j], 0]) for j in range(i, 29): lines[j].set_data([], []) return lines animation.FuncAnimation(fig, animate, init_func=init, frames=30, interval=500, blit=True) plt.legend(loc='upper right', numpoints=1) plt.show()
def filter_freqs(lowcut, highcut, fs, plot=False, corners=4): ''' The frequency band information should technically be the amplitude spectrum of the filtered seismograms, but the amplitude spectrum of the bandpass filter is sufficient. Here we use a bandpass butterworth filter. The function freq band takes 3 arguments: lowcut = low end of bandpass (in Hz) highcut = high end of bandpass (in Hz) fs = sample rate (1.0/dt) It returns two vectors: omega = frequency axis (in rad/s) amp = frequency response of the filter ''' #Define bandpass parameters nyquist = 0.5 * fs fmin = lowcut/nyquist fmax = highcut/nyquist #Make filter shape b, a = iirfilter(corners, [fmin,fmax], btype='band', ftype='butter') #Determine freqency response freq_range = np.linspace(0,0.15,200) w, h = freqz(b,a,worN=freq_range) omega = fs * w # in rad/s omega_hz = (fs * w) / (2*np.pi) # in hz amp = abs(h) if(plot == True): #Checks---------------- #plt.semilogx(omega,amp) #plt.axvline(1/10.0) #plt.axvline(1/25.0) #plt.axhline(np.sqrt(0.5)) plt.plot(omega,amp) plt.xlabel('frequency (rad/s)') plt.ylabel('amplitude') plt.show() return omega, amp
def plot_batches(fulldata, cols=None, out_file=None, site_labels='left'): fulldata = fulldata.sort_values(by=['database', 'site']).copy() sites = fulldata.site.values.ravel().tolist() if cols is None: numdata = fulldata.select_dtypes([np.number]) else: numdata = fulldata[cols] numdata = numdata[cols] colmin = numdata.min() numdata = (numdata - colmin) colmax = numdata.max() numdata = numdata / colmax fig, ax = plt.subplots(figsize=(20, 10)) ax.imshow(numdata.values, cmap=plt.cm.viridis, interpolation='nearest', aspect='auto') locations = [] spines = [] fulldata['index'] = range(len(fulldata)) for site in list(set(sites)): indices = fulldata.loc[fulldata.site == site, 'index'].values.ravel().tolist() locations.append(int(np.average(indices))) spines.append(indices[0]) if site_labels == 'right': ax.yaxis.tick_right() ax.yaxis.set_label_position("right") plt.xticks(range(numdata.shape[1]), numdata.columns.ravel().tolist(), rotation='vertical') plt.yticks(locations, list(set(sites))) for line in spines[1:]: plt.axhline(y=line, color='w', linestyle='-') ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) # ax.spines['left'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.grid(False) ticks_font = FontProperties( family='FreeSans', style='normal', size=14, weight='normal', stretch='normal') for label in ax.get_yticklabels(): label.set_fontproperties(ticks_font) ticks_font = FontProperties( family='FreeSans', style='normal', size=12, weight='normal', stretch='normal') for label in ax.get_xticklabels(): label.set_fontproperties(ticks_font) if out_file is not None: fig.savefig(out_file, bbox_inches='tight', pad_inches=0, dpi=300) return fig
def mult_regression(wine_set): # center quantitative IVs for regression analysis w = wine_set['quality'] wine_set = wine_set - wine_set.mean() wine_set['quality'] = w print ("OLS multivariate regression model") # first i have run with all columns; than chose the most significant for each wine set and rerun: if len(wine_set) < 2000: # for red model1 = smf.ols( formula="quality ~ volatile_acidity + chlorides + pH + sulphates + alcohol", data=wine_set) else: # for white model1 = smf.ols( formula="quality ~ volatile_acidity + density + pH + sulphates + alcohol", data=wine_set) results1 = model1.fit() print(results1.summary()) # q-q plot for normality qq = sm.qqplot(results1.resid, line = 'r') plt.show() # plot of residuals stdres = pd.DataFrame(results1.resid_pearson) plt.plot(stdres, 'o', ls = 'None') l = plt.axhline(y=0, color = 'r') plt.ylabel('Standardized redisual') plt.xlabel('Observation number') plt.show() # # diagnostic plots # figure1 = plt.figure(figsize=(12, 8)) # figure1 = sm.graphics.plot_regress_exog(results1, "alcohol", fig = figure1) # plt.show() # # figure1 = plt.figure(figsize=(12, 8)) # figure1 = sm.graphics.plot_regress_exog(results1, "sulphates", fig = figure1) # plt.show() # leverage plot figure1 = sm.graphics.influence_plot(results1, size=8) plt.show() # call(mult_regression) # ____________________________ Logistic Regression _____________________
def plot_dendro(linkage, logname, cutoff, color_list,clusters_list): """ DESCRIPTION This function will create the dendrogram graph with the corresponding cluster color. Args: linkage (numpy array) : linkage matrix output (str) : output logfile name cutoff (float) : cutoff used for clustering color_list (list) : HEX code color for each cluster cluster_list (list) : list of all cluster (Cluster object) Returns: None """ if mpl.__version__[0] == "2": STYLE = "classic" if STYLE in plt.style.available: plt.style.use(STYLE) fig = plt.figure() #Convert RGB color to HEX color color_hex = [mpl.colors.rgb2hex(x) for x in color_list] sch.set_link_color_palette(color_hex) #clusters_list color_member = {} for cl in clusters_list: for frm in cl.frames: color_member[frm] = mpl.colors.rgb2hex(color_list[cl.id-1]) #Attribute the correct color for each branch. #adapte from Ulrich Stern code in StackOverflow http://stackoverflow.com/a/38208611 link_cols = {} for i, i12 in enumerate(linkage[:,:2].astype(int)): c1, c2 = (link_cols[x] if x > len(linkage) else color_member[x] for x in i12) link_cols[i+1+len(linkage)] = c1 if c1 == c2 else "#808080" #Dendrogram creation # Override the default linewidth. den = sch.dendrogram(linkage, color_threshold=float(cutoff), above_threshold_color="#808080", link_color_func=lambda x: link_cols[x]) #Graph parameters plt.title("Clustering Dendrogram") ax = plt.axes() ax.set_xticklabels([]) plt.axhline(y=float(cutoff), color = "grey") # cutoff value vertical line ax.set_ylabel("Distance (AU)") ax.set_xlabel("Frames") plt.savefig("{0}/{0}-den.png".format(logname), format="png", dpi=DPI, transparent=True) plt.close()