我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pylab.show()。
def freq_from_HPS(sig, fs): """ Estimate frequency using harmonic product spectrum (HPS) """ windowed = sig * blackmanharris(len(sig)) from pylab import subplot, plot, log, copy, show # harmonic product spectrum: c = abs(rfft(windowed)) maxharms = 3 #subplot(maxharms, 1, 1) #plot(log(c)) for x in range(2, maxharms): a = copy(c[::x]) # Should average or maximum instead of decimating # max(c[::x],c[1::x],c[2::x],...) c = c[:len(a)] i = argmax(abs(c)) true_i = parabolic(abs(c), i)[0] print 'Pass %d: %f Hz' % (x, fs * true_i / len(windowed)) c *= a #subplot(maxharms, 1, x) #plot(log(c)) #show()
def view_trigger_snippets_bis(trigger_snippets, elec_index, save=None): fig = pylab.figure() ax = fig.add_subplot(1, 1, 1) for n in xrange(0, trigger_snippets.shape[2]): y = trigger_snippets[:, elec_index, n] x = numpy.arange(- (y.size - 1) / 2, (y.size - 1) / 2 + 1) b = 0.5 + 0.5 * numpy.random.rand() ax.plot(x, y, color=(0.0, 0.0, b), linestyle='solid') ax.grid(True) ax.set_xlim([numpy.amin(x), numpy.amax(x)]) ax.set_xlabel("time") ax.set_ylabel("amplitude") if save is None: pylab.show() else: pylab.savefig(save) pylab.close(fig) return
def view_dataset(X, color='blue', title=None, save=None): n_components = 2 pca = PCA(n_components) pca.fit(X) x = pca.transform(X) fig = pylab.figure() ax = fig.add_subplot(1, 1, 1) ax.scatter(x[:, 0], x[:, 1], c=color, s=5, lw=0.1) ax.grid(True) if title is None: ax.set_title("Dataset ({} samples)".format(X.shape[0])) else: ax.set_title(title + " ({} samples)".format(X.shape[0])) ax.set_xlabel("1st component") ax.set_ylabel("2nd component") if save is None: pylab.show() else: pylab.savefig(save) pylab.close(fig) return
def view_loss_curve(losss, title=None, save=None): '''Plot loss curve''' x_min = 1 x_max = len(losss) - 1 fig = pylab.figure() ax = fig.gca() ax.semilogy(range(x_min, x_max + 1), losss[1:], color='blue', linestyle='solid') ax.grid(True, which='both') if title is None: ax.set_title("Loss curve") else: ax.set_title(title) ax.set_xlabel("iteration") ax.set_ylabel("loss") ax.set_xlim([x_min - 1, x_max + 1]) if save is None: pylab.show() else: pylab.savefig(save) pylab.close(fig) return
def display_wav(filename): input_data = read(filename) audio_in = input_data[1] samples = len(audio_in) fig = pylab.figure(); print samples/44100.0," seconds" k = 0 plot_data_out = [] for i in xrange(samples): plot_data_out.append(audio_in[k]/32768.0) k = k+1 pdata = numpy.array(plot_data_out, dtype=numpy.float) pylab.plot(pdata) pylab.grid(True) pylab.ion() pylab.show()
def display_pr_curve(precision, recall): # following examples from sklearn # TODO: f1 operating point import pylab as plt # Plot Precision-Recall curve plt.clf() plt.plot(recall, precision, label='Precision-Recall curve') plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.title('Precision-Recall example: Max f1={0:0.2f}'.format(max_f1)) plt.legend(loc="lower left") plt.show()
def disp(iimg, label = "", gray=False): """ Display an image using pylab """ try: import pylab dimage = iimg.copy() if iimg.ndim==3: dimage[...,0] = iimg[...,2] dimage[...,2] = iimg[...,0] pylab.imshow(dimage, interpolation='none') if gray: pylab.gray() #pylab.gca().format_coord = format_coord pylab.text(1500, -30, label) pylab.axis('off') pylab.show() except ImportError: print "Module pylab not available"
def PlotMultipleRuns(Alg, nruns=20, fname=None): '''Plot "nruns" runs of a given algorithm to show performance and variability across runs.''' if fname: runs = scipy.genfromtxt(fname) else: runs = [] for i in range(nruns): bestSol, fitHistory = tsp.TSP(200, Alg, 3000, 30, seed=None, coordfile='tmp.txt') runs.append(fitHistory) fname = 'MultRuns-' + str(Alg) + '.txt' runs = scipy.array(runs) scipy.savetxt(fname, runs) # plotting Xs = scipy.linspace(0, runs.shape[1] * 1000, runs.shape[1]) for i in range(runs.shape[0]): pl.plot(Xs, runs[i, :]) pl.show()
def LongMC3(fname=None): '''Plot a single long MC3 run to demonstrate high performance but slow convergence.''' if fname: run = scipy.genfromtxt(fname) else: bestSol, run = tsp.TSP(200, 'MC3', 20000, 10, seed=None, coordfile='tmp.txt') fname = 'ExampleOutput/MC3-Long.txt' run = scipy.array(run) scipy.savetxt(fname, run) # plotting Xs = range(0, run.shape[0] * 1000, 1000) pl.plot(Xs, run) pl.show()
def LongSA(fname=None): '''Plot a single long SA run to demonstrate performance under slower cooling schedule.''' if fname: run = scipy.genfromtxt(fname) else: bestSol, run = tsp.TSP(200, 'SA', 20000, 'placeholder', seed=None, coordfile='tmp.txt') fname = 'ExampleOutput/SA-Long.txt' run = scipy.array(run) scipy.savetxt(fname, run) # plotting Xs = range(0, run.shape[0] * 1000, 1000) pl.plot(Xs, run) pl.show()
def PlotProps(pars): import numpy as np import pylab as pl import vanGenuchten as vg psi = np.linspace(-10, 2, 200) pl.figure pl.subplot(3, 1, 1) pl.plot(psi, vg.thetaFun(psi, pars)) pl.ylabel(r'$\theta(\psi) [-]$') pl.subplot(3, 1, 2) pl.plot(psi, vg.CFun(psi, pars)) pl.ylabel(r'$C(\psi) [1/m]$') pl.subplot(3, 1, 3) pl.plot(psi, vg.KFun(psi, pars)) pl.xlabel(r'$\psi [m]$') pl.ylabel(r'$K(\psi) [m/d]$') # pl.show()
def buildArgsParser(): DESCRIPTION = "Generate samples from a Conv Deep NADE model." p = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=argparse.ArgumentDefaultsHelpFormatter) p.add_argument('experiment', type=str, help='folder where to find a trained ConvDeepNADE model') p.add_argument('count', type=int, help='number of samples to generate.') p.add_argument('--out', type=str, help='name of the samples file') # General parameters (optional) p.add_argument('--seed', type=int, help='seed used to generate random numbers. Default: 1234', default=1234) p.add_argument('--view', action='store_true', help="show samples.") p.add_argument('-v', '--verbose', action='store_true', help='produce verbose output') p.add_argument('-f', '--force', action='store_true', help='permit overwriting') return p
def plotPopScore(population, fitness=False): """ Plot the population score distribution Example: >>> Interaction.plotPopScore(population) :param population: population object (:class:`GPopulation.GPopulation`) :param fitness: if True, the fitness score will be used, otherwise, the raw. :rtype: None """ score_list = getPopScores(population, fitness) pylab.plot(score_list, 'o') pylab.title("Plot of population score distribution") pylab.xlabel('Individual') pylab.ylabel('Score') pylab.grid(True) pylab.show() # -----------------------------------------------------------------
def plotHistPopScore(population, fitness=False): """ Population score distribution histogram Example: >>> Interaction.plotHistPopScore(population) :param population: population object (:class:`GPopulation.GPopulation`) :param fitness: if True, the fitness score will be used, otherwise, the raw. :rtype: None """ score_list = getPopScores(population, fitness) n, bins, patches = pylab.hist(score_list, 50, facecolor='green', alpha=0.75, normed=1) pylab.plot(bins, pylab.normpdf(bins, numpy.mean(score_list), numpy.std(score_list)), 'r--') pylab.xlabel('Score') pylab.ylabel('Frequency') pylab.grid(True) pylab.title("Plot of population score distribution") pylab.show() # -----------------------------------------------------------------
def fastLapModel(xList, labels, names, multiple=0, full_set=0): X = numpy.array(xList) y = numpy.array(labels) featureNames = [] featureNames = numpy.array(names) # take fixed holdout set 30% of data rows xTrain, xTest, yTrain, yTest = train_test_split( X, y, test_size=0.30, random_state=531) # for final model (no CV) if full_set: xTrain = X yTrain = y check_set(xTrain, xTest, yTrain, yTest) print "Fitting the model to the data set..." # train random forest at a range of ensemble sizes in order to see how the # mse changes mseOos = [] m = 10 ** multiple nTreeList = range(500 * m, 1000 * m, 100 * m) # iTrees = 10000 for iTrees in nTreeList: depth = None maxFeat = int(np.sqrt(np.shape(xTrain)[1])) + 1 # try tweaking RFmd = ensemble.RandomForestRegressor(n_estimators=iTrees, max_depth=depth, max_features=maxFeat, oob_score=False, random_state=531, n_jobs=-1) # RFmd.n_features = 5 RFmd.fit(xTrain, yTrain) # Accumulate mse on test set prediction = RFmd.predict(xTest) mseOos.append(mean_squared_error(yTest, prediction)) # plot training and test errors vs number of trees in ensemble plot.plot(nTreeList, mseOos) plot.xlabel('Number of Trees in Ensemble') plot.ylabel('Mean Squared Error') #plot.ylim([0.0, 1.1*max(mseOob)]) plot.show() print("MSE") print(mseOos[-1]) return xTrain, xTest, yTrain, yTest, RFmd
def plot_importance(names, model, savefig=True): featureNames = numpy.array(names) featureImportance = model.feature_importances_ featureImportance = featureImportance / featureImportance.max() sorted_idx = numpy.argsort(featureImportance) barPos = numpy.arange(sorted_idx.shape[0]) + .5 plot.barh(barPos, featureImportance[sorted_idx], align='center') plot.yticks(barPos, featureNames[sorted_idx]) plot.xlabel('Variable Importance') plot.subplots_adjust(left=0.2, right=0.9, top=0.9, bottom=0.1) if savefig: dt_ = datetime.datetime.now().strftime('%d%b%y_%H%M') plt.savefig("../graphs/featureImportance_" + dt_ + ".png") plot.show() # Plot prediction save the graph with a timestamp
def plot_pred(y_predicted, y, savefig=True): # y_predicted.reset_index(drop=1, inplace=1) index = np.argsort(y) y = y[index] # y.shape yhat = y_predicted[index] yy = pd.DataFrame([y, yhat]) if yy.shape[1] > yy.shape[0]: yy = yy.T yy.reset_index(drop=0, inplace=1) plt.scatter(yy.index, yy[1], s=.4) plt.plot(yy.index, yy[0], ls='-', color='red', linewidth=.5) if savefig: dt_ = datetime.datetime.now().strftime('%d%b%y_%H%M') plt.savefig("../graphs/" + dt_ + ".png") plt.show() # Check the data before regression (no Na, size, etc)
def backgroundPeakValue(img, bins=500): f = FitHistogramPeaks(img, bins=bins, bins2=300) bgp = getBackgroundPeak(f.fitParams) ind = int(bgp[1]) if ind < 0: ind = 0 # y = f.yvals[ind:] # i = np.argmax(np.diff(y) > 0) # bgmaxpos = ind # + i # print(f.xvals[bgmaxpos], bgmaxpos) # import pylab as plt # plt.plot(f.xvals, f.yvals) # plt.show() return f.xvals[ind]
def interpolate2dDiffusion(arr1, arr2, steps=10, diffusivity=0.2): psf = np.zeros((5, 5)) numbaGaussian2d(psf, 1, 1) # plt.imshow(psf) # plt.show() last = arr1 out = [] for s in range(steps): next = np.zeros_like(arr1) diff = diffusivity * (last - arr2) # plt.imshow(diff) # plt.show() weightedConvolution(last, next, diff, psf) out.append(next) last = next return out
def _visualize(grid, device, img, gen): # for debugging: # show intermediate steps of iteration # in [vignettingDiscreteSteps] import pylab as plt fig, ax = plt.subplots(1, 3) ax[0].set_title('device') ax[0].imshow(device, interpolation='none') ax[1].set_title('average') ax[1].imshow(grid, interpolation='none') ax[2].set_title('grid') im = ax[2].imshow(img, interpolation='none') for x, y in gen: ax[2].plot(x, y) fig.colorbar(im) plt.show()
def generate_inverted_sinewave_dataset(N = 1000, f = 1.0, p = 0.0, a1 = 1.0, a2 = 0.3): """models_actinf.generate_inverted_sinewave_dataset Generate the inverted sine dataset used in Bishop's (Bishop96) mixture density paper Returns: - matrices X, Y """ X = np.linspace(0,1,N) # FIXME: include phase p Y = a1 * X + a2 * np.sin(f * (2 * 3.1415926) * X) + np.random.uniform(-0.1, 0.1, N) X,Y = Y[:,np.newaxis],X[:,np.newaxis] # pl.subplot(211) # pl.plot(Y, X, "ko", alpha=0.25) # pl.subplot(212) # pl.plot(X, Y, "ko", alpha=0.25) # pl.show() return X,Y
def plot_success_functions(): data_dir = "/Users/Chen/data/ngas_logs" lru_yd = np.load("{0}/{1}".format(data_dir, 'yd_lru_ingest_correct.npy')) lfu_yd = np.load("{0}/{1}".format(data_dir, 'yd_lfu_ingest_correct.npy')) liat_yd = np.load("{0}/{1}".format(data_dir, 'yd_liat_ingest_correct.npy')) lrud_yd = np.load("{0}/{1}".format(data_dir, 'yd_lrud_ingest_correct.npy')) lnr_yd = np.load("{0}/{1}".format(data_dir, 'yd_lnr_ingest_correct.npy')) law_yd = np.load("{0}/{1}".format(data_dir, 'yd_law_ingest_correct.npy')) #liat_yd_imiat = np.load("{0}/{1}".format(data_dir, 'yd_liat_ingest_max_iat.npy')) ax1 = plot_success_function(lru_yd, label='Least Recently Used', show=False) #plot_success_function(lru_yd, label='LRU - default on disk', line='--', show=False, init_on_tape=False, ax=ax1) plot_success_function(lfu_yd, label='Least Frequently Used', line='--', lcolor='skyblue', show=False, ax=ax1) #plot_success_function(lfu_yd, label='LFU - default on disk', lcolor='r', line='--', init_on_tape=False, show=False, ax=ax1) plot_success_function(liat_yd, label='Longest Inter-Arrival Time', line=':', lcolor='darkorchid', show=False, ax=ax1) plot_success_function(law_yd, label='Largest Age Weight (DMF)', line='-', lcolor='k', show=False, ax=ax1) #plot_success_function(liat_yd, label='LIAT - default on disk', lcolor='g', line='--', init_on_tape=False, ax=ax1) #plot_success_function(liat_yd_imiat, label='LIAT - ingest max iat', lcolor='g', line='-.', ax=ax1) plot_success_function(lnr_yd, label='Longest Next Access (Optimal)', line='--', lcolor='deeppink', show=False, ax=ax1, lw=3.0) plot_ws_success_function(lru_yd, ax=ax1, lw=3.0) plot_success_function(lrud_yd, label='Longest Reuse Distance', line='-.', lcolor='lime', show=True, ax=ax1, lw=4.0)
def ex2(): x = np.linspace(-10, 10) # "--" = dashed line plt.plot(x, np.sin(x), "--", label="sinus") plt.plot(x, np.cos(x), label="cosinus") # Show the legend using the labels above plt.legend() # The trick here is we have to make another plot on top of the two others. pi2 = np.pi/2 # Find B such that (-B * pi/2) >= -10 > ((-B-1) * pi/2), i.e. the # first multiple of pi/2 higher than -10. b = pi2*int(-10.0/pi2) # x2 is all multiples of pi/2 between -10 and 10. x2 = np.arange(b, 10, pi2) # "b." = blue dots plt.plot(x2, np.sin(x2), "b.") plt.show()
def plot(self): """ Plot startup data. """ import pylab print("Plotting result...", end="") avg_data = self.average_data() avg_data = self.__sort_data(avg_data, False) if len(self.raw_data) > 1: err = self.stdev_data() sorted_err = [err[k] for k in list(zip(*avg_data))[0]] else: sorted_err = None pylab.barh(range(len(avg_data)), list(zip(*avg_data))[1], xerr=sorted_err, align='center', alpha=0.4) pylab.yticks(range(len(avg_data)), list(zip(*avg_data))[0]) pylab.xlabel("Average startup time (ms)") pylab.ylabel("Plugins") pylab.show() print(" done.")
def view_(_pred,_lable): fname = ['Captcha/lv3/%i.jpg' %i for i in range(20)] img = [] for fn in fname: img.append(Image.open(open(fn))) #img.append(misc.imread(fn).astype(np.float)) for i in range(len(img)): pylab.subplot(4,5,i+1); pylab.axis('off') pylab.imshow(img[i]) #pylab.imshow( np.dot(np.array(img[i])[...,:3],[0.299,0.587,0.114]) , cmap=plt.get_cmap("gray")) #pylab.text(40,60,_pred[i],color = 'b') if ( _pred[i] == _lable[i] ): pylab.text(40,65,_pred[i],color = 'b',size = 15) else: pylab.text(40,65,_pred[i],color = 'r',size = 15) pylab.text(40,92,_lable[i],color = 'g',size = 15) pylab.show()
def show(self): # pl.semilogy(self.theta, self.omega) # , label = '$L =%.1f m, $'%self.l + '$dt = %.2f s, $'%self.dt + '$\\theta_0 = %.2f radians, $'%self.theta[0] + '$q = %i, $'%self.q + '$F_D = %.2f, $'%self.F_D + '$\\Omega_D = %.1f$'%self.Omega_D) pl.plot(self.theta_phase ,self.omega_phase, '.', label = '$t \\approx 2\\pi n / \\Omega_D$') pl.xlabel('$\\theta$ (radians)') pl.ylabel('$\\omega$ (radians/s)') pl.legend() # pl.text(-1.4, 0.3, '$\\omega$ versus $\\theta$ $F_D = 1.2$', fontsize = 'x-large') pl.title('Chaotic Regime') # pl.show() # pl.semilogy(self.time_array, self.delta) # pl.legend(loc = 'upper center', fontsize = 'small') # pl.xlabel('$time (s)$') # pl.ylabel('$\\Delta\\theta (radians)$') # pl.xlim(0, self.T) # pl.ylim(float(input('ylim-: ')),float(input('ylim+: '))) # pl.ylim(1E-11, 0.01) # pl.text(4, -0.15, 'nonlinear pendulum - Euler-Cromer method') # pl.text(10, 1E-3, '$\\Delta\\theta versus time F_D = 0.5$') # pl.title('Simple Harmonic Motion') pl.title('Chaotic Regime')
def show_log(self): # pl.subplot(121) pl.semilogy(self.time_array, self.delta, 'c') pl.xlabel('$time (s)$') pl.ylabel('$\\Delta\\theta$ (radians)') pl.xlim(0, self.T) # pl.ylim(1E-11, 0.01) pl.text(42, 1E-7, '$\\Delta\\theta$ versus time $F_D = 1.2$', fontsize = 'x-large') pl.title('Chaotic Regime') pl.show() # def show_log_sub122(self): # pl.subplot(122) # pl.semilogy(self.time_array, self.delta, 'g') # pl.xlabel('$time (s)$') # pl.ylabel('$\\Delta\\theta$ (radians)') # pl.xlim(0, self.T) # pl.ylim(1E-6, 100) # pl.text(20, 1E-5, '$\\Delta\\theta$ versus time $F_D = 1.2$', fontsize = 'x-large') # pl.title('Chaotic Regime') # pl.show()
def multi_show(self): for i in range(2): a = simple_harmonic_motion(time_step = float(input('time step: ')), time_duration = float(input('time duration: ')), initial_theta = float(input('initial theta: ')), length = float(input('length: ')), strength_of_damping = float(input('stength of damping: ')), amplitude = float(input('amplitude of driving force: ')), anguluar_frequency = float(input('angular frequency of driving force: '))) a.calculate() a.show() pl.show() #class please_input(): # string_input = input('xlocation ,ylocation: ') # numbers = [float(n) for n in string_input.split()] # x = numbers[0] # y = numbers[1] #b = simple_harmonic_motion() #b.calculate_delta() #b.show()
def show(self): # pl.semilogy(self.theta, self.omega) # , label = '$L =%.1f m, $'%self.l + '$dt = %.2f s, $'%self.dt + '$\\theta_0 = %.2f radians, $'%self.theta[0] + '$q = %i, $'%self.q + '$F_D = %.2f, $'%self.F_D + '$\\Omega_D = %.1f$'%self.Omega_D) pl.plot(self.time_array,self.delta) # pl.show() # pl.semilogy(self.time_array, self.delta) # pl.legend(loc = 'upper center', fontsize = 'small') # pl.xlabel('$time (s)$') # pl.ylabel('$\\Delta\\theta (radians)$') # pl.xlim(0, self.T) # pl.ylim(float(input('ylim-: ')),float(input('ylim+: '))) # pl.ylim(1E-11, 0.01) # pl.text(4, -0.15, 'nonlinear pendulum - Euler-Cromer method') # pl.text(10, 1E-3, '$\\Delta\\theta versus time F_D = 0.5$') # pl.title('Simple Harmonic Motion') # pl.title('Chaotic Regime')
def show_complex(self): font = {'family': 'serif', 'color': 'k', 'weight': 'normal', 'size': 16, } pl.title('The Trajectory of Tageted Baseball\n with air flow in adiabatic model', fontdict = font) pl.plot(self.x, self.y, label = '$v_0 = %.5f m/s$'%self.v0 + ', ' + '$\\theta = %.4f \degree$'%self.theta) pl.xlabel('x $m$') pl.ylabel('y $m$') pl.xlim(0, 300) pl.ylim(-100, 20) pl.grid() pl.legend(loc = 'upper right', shadow = True, fontsize = 'small') pl.text(15, -90, 'scan to approach the minimum velocity and corresponding launching angle', fontdict = font) pl.show()
def show_simple(self): font = {'family': 'serif', 'color': 'k', 'weight': 'normal', 'size': 16, } pl.title('The Trajectory of Tageted Baseball\n with air flow in adiabatic model', fontdict = font) pl.plot(self.x, self.y, label ='$\\alpha = %.0f \degree$'%self.alpha) pl.xlabel('x $m$') pl.ylabel('y $m$') pl.xlim(0, 400) pl.ylim(-100, 200) pl.grid() pl.legend(loc = 'upper right', shadow = True, fontsize = 'medium') pl.text(5, -80, 'trojectories varing with angles of wind', fontdict = font) pl.show()
def double_scan(self): v_0 = 81.09589 while 0 <= v_0: theta_0 = 7.1610 while 7.1610 <= theta_0 < 7.1620: t = targeted_baseball(v_0, theta_0, 0.01, 10, 135) t.calculate() t.show() if a < 220: theta_0 = theta_0 + 0.0001 else: print(a, '\n', v_0,'\n', theta_0) break v_0 = v_0 + 0.00001 if a >= 220: break
def show_results(self): font = {'family': 'serif', 'color': 'k', 'weight': 'normal', 'size': 14, } pl.plot(self.x, self.y, 'c', label='firing angle = 45°') pl.title('The Trajectory of a Cannon Shell', fontdict = font) pl.xlabel('x (k$m$)') pl.ylabel('y ($km$)') pl.xlim(0, 60) pl.ylim(0, 20) pl.grid(True) pl.legend(loc='upper right', shadow=True, fontsize='large') pl.text(41, 16, 'Only with air drag', fontdict = font) pl.show()
def show_results(self): font = {'family': 'serif', 'color': 'k', 'weight': 'normal', 'size': 12, } pl.plot(self.x, self.y, 'c', label='firing angle = 45°') pl.title('The Trajectory of a Cannon Shell', fontdict = font) pl.xlabel('x (k$m$)') pl.ylabel('y ($km$)') pl.xlim(0, 60) pl.ylim(0, 20) pl.grid(True) pl.legend(loc='upper right', shadow=True, fontsize='large') pl.text(34, 16, ' With both air drag and \n reduced air density-isothermal', fontdict = font) pl.show()
def show_results(self): font = {'family': 'serif', 'color': 'k', 'weight': 'normal', 'size': 12, } pl.plot(self.x, self.y, 'c', label='firing angle = 45°') pl.title('The Trajectory of a Cannon Shell', fontdict = font) pl.xlabel('x (k$m$)') pl.ylabel('y ($km$)') pl.xlim(0, 60) pl.ylim(0, 20) pl.grid(True) pl.legend(loc='upper right', shadow=True, fontsize='large') pl.text(34.5, 16, ' With both air drag and \n reduced air density-adiabatic', fontdict = font) pl.show()
def DrawDvs(pl, closes, curve, sign, dvs, pandl, sh, title, leag=None, lad=None ): pl.figure pl.subplot(311) pl.title("id:%s Sharpe ratio: %.2f"%(str(title),sh)) pl.plot(closes) DrawLine(pl, sign, closes) pl.subplot(312) pl.grid() if dvs != None: pl.plot(dvs) if isinstance(curve, np.ndarray): DrawZZ(pl, curve, 'r') if leag != None: pl.plot(leag, 'r') if lad != None: pl.plot(lad, 'b') #pl.plot(stock.GuiYiHua(closes[:i])[60:]) pl.subplot(313) pl.plot(sign) pl.plot(pandl) pl.show() pl.close()
def DrawDvsAndZZ(pl, dvs, zz, closes=None): """dvs?zz??????; dvs : ????closes, """ dvs = np.array(dvs) pl.figure if closes == None: pl.plot(dvs) pl.plot(zz[:,0], zz[:,1], 'r') else: pl.subplot(211) pl.plot(closes) pl.grid() pl.subplot(212) pl.grid() pl.plot(dvs) pl.plot(zz[:,0], zz[:,1], 'r') pl.show() pl.close()
def DrawHist(pl, shs): """??????, shs: ??? array""" shs = np.array(shs, dtype=float) #print "mean: %.2f"%shs.mean() shs = shs[np.isnan(shs) == False] if len(shs)>0: pl.figure pl.hist(shs) def ShowHitCount(shs): #???? go_count = len(shs) - len(shs[np.isnan(shs)]) #??? if len(shs) != 0: v = float(go_count)/ float(len(shs)) #print("trade rato:%.2f%%"%(v*100)) #????? if go_count>0: v = float(len(shs[shs>0]))/float(go_count) #print("win rato: %.2f%%"%(v*100)) pl.show() #ShowHitCount(shs)
def _test_AsynDrawKline(self): code = '300033' start_day = '2017-8-25' #df = stock.getHisdatDataFrameFromRedis(code, start_day) df = stock.getFiveHisdatDf(code, start_day=start_day) import account account = account.LocalAcount(account.BackTesting()) #???????? indexs = agl.GenRandomArray(len(df), 3) trade_bSell = [0,1,0] df_trades = df[df.index.map(lambda x: x in df.index[indexs])] df_trades = df_trades.copy() df_trades[AsynDrawKline.enum.trade_bSell] = trade_bSell plt.ion() for i in range(10): AsynDrawKline.drawKline(df[i*10:], df_trades) plt.ioff() #plt.show() #???????? ????????
def _test_boll(self): code = '300113' df_five_hisdat = getFiveHisdatDf(code,'2017-5-1') #print(closes) #upper, middle, lower = BOLL(df_five_hisdat['c']) #print(upper[-1], lower[-1]) upper, middle, lower = TDX_BOLL(df_five_hisdat['c']) print upper[-10:] print middle[-10:] print lower[-10:] #df_five_hisdat['upper'] = upper #df_five_hisdat['lower'] = lower #df_five_hisdat['mid'] = middle #df = df_five_hisdat[['upper', 'c', 'mid', 'lower']] #df.plot() #pl.show() upper, middle, lower, boll_w = TDX_BOLL2(df_five_hisdat['c']) print boll_w
def plot(self): #?????????????????? pl.figure #????? a = [] for h in self.weituo_historys: a.append(h.price) a = GuiYiHua(a) pl.plot(a, 'b') #??? a = np.array(self.total_moneys) a = GuiYiHua(a) pl.plot(a, 'r') pl.legend(['price list', 'money list']) pl.show() pl.close() #???????????????, ??????????
def Unittest_Kline(): """""" kline = Guider("600100", "") print(kline.getData(0).date, kline.getLastData().date) #kline.myprint() obv = kline.OBV() pl.figure pl.subplot(2,1,1) pl.plot(kline.getCloses()) pl.subplot(2,1,2) ma,m2,m3 = kline.MACD() pl.plot(ma) pl.plot(m2,'r') left = np.arange(0, len(m3)) pl.bar(left,m3) #pl.plot(obv, 'y') pl.show() #Unittest_Kstp() # #??????????? #----------------------------------------------------------------------
def visualize_reconstruction(xp, model, x, visualization_dir, epoch, gpu=False): x_variable = chainer.Variable(xp.asarray(x)) _x = model.decode(model.encode(x_variable), test=True) _x.to_cpu() _x = _x.data fig = pylab.gcf() fig.set_size_inches(8.0, 8.0) pylab.clf() pylab.gray() for m in range(50): i = m / 10 j = m % 10 pylab.subplot(10, 10, 20 * i + j + 1, xticks=[], yticks=[]) pylab.imshow(x[m].reshape((28, 28)), interpolation="none") pylab.subplot(10, 10, 20 * i + j + 10 + 1, xticks=[], yticks=[]) pylab.imshow(_x[m].reshape((28, 28)), interpolation="none") # pylab.imshow(np.clip((_x_batch.data[m] + 1.0) / 2.0, 0.0, 1.0).reshape( # (config.img_channel, config.img_width, config.img_width)), interpolation="none") pylab.axis("off") pylab.savefig("{}/reconstruction_{}.png".format(visualization_dir, epoch)) # pylab.show()
def view_waveforms_clusters(data, halo, threshold, templates, amps_lim, n_curves=200, save=False): nb_templates = templates.shape[1] n_panels = numpy.ceil(numpy.sqrt(nb_templates)) mask = numpy.where(halo > -1)[0] clust_idx = numpy.unique(halo[mask]) fig = pylab.figure() square = True center = len(data[0] - 1)//2 for count, i in enumerate(xrange(nb_templates)): if square: pylab.subplot(n_panels, n_panels, count + 1) if (numpy.mod(count, n_panels) != 0): pylab.setp(pylab.gca(), yticks=[]) if (count < n_panels*(n_panels - 1)): pylab.setp(pylab.gca(), xticks=[]) subcurves = numpy.where(halo == clust_idx[count])[0] for k in numpy.random.permutation(subcurves)[:n_curves]: pylab.plot(data[k], '0.5') pylab.plot(templates[:, count], 'r') pylab.plot(amps_lim[count][0]*templates[:, count], 'b', alpha=0.5) pylab.plot(amps_lim[count][1]*templates[:, count], 'b', alpha=0.5) xmin, xmax = pylab.xlim() pylab.plot([xmin, xmax], [-threshold, -threshold], 'k--') pylab.plot([xmin, xmax], [threshold, threshold], 'k--') #pylab.ylim(-1.5*threshold, 1.5*threshold) ymin, ymax = pylab.ylim() pylab.plot([center, center], [ymin, ymax], 'k--') pylab.title('Cluster %d' %i) if nb_templates > 0: pylab.tight_layout() if save: pylab.savefig(os.path.join(save[0], 'waveforms_%s' %save[1])) pylab.close() else: pylab.show() del fig
def view_artefact(data, save=False): fig = pylab.figure() pylab.plot(data.T) if save: pylab.savefig(os.path.join(save[0], 'artefact_%s' %save[1])) pylab.close() else: pylab.show() del fig
def view_trigger_snippets(trigger_snippets, chans, save=None): # Create output directory if necessary. if os.path.exists(save): for f in os.listdir(save): p = os.path.join(save, f) os.remove(p) os.removedirs(save) os.makedirs(save) # Plot figures. fig = pylab.figure() for (c, chan) in enumerate(chans): ax = fig.add_subplot(1, 1, 1) for n in xrange(0, trigger_snippets.shape[2]): y = trigger_snippets[:, c, n] x = numpy.arange(- (y.size - 1) / 2, (y.size - 1) / 2 + 1) b = 0.5 + 0.5 * numpy.random.rand() ax.plot(x, y, color=(0.0, 0.0, b), linestyle='solid') y = numpy.mean(trigger_snippets[:, c, :], axis=1) x = numpy.arange(- (y.size - 1) / 2, (y.size - 1) / 2 + 1) ax.plot(x, y, color=(1.0, 0.0, 0.0), linestyle='solid') ax.grid(True) ax.set_xlim([numpy.amin(x), numpy.amax(x)]) ax.set_title("Channel %d" %chan) ax.set_xlabel("time") ax.set_ylabel("amplitude") if save is not None: # Save plot. filename = "channel-%d.png" %chan path = os.path.join(save, filename) pylab.savefig(path) fig.clf() if save is None: pylab.show() else: pylab.close(fig) return
def view_mahalanobis_distribution(data_1, data_2, save=None): '''Plot Mahalanobis distribution Before and After''' fig = pylab.figure() ax = fig.add_subplot(1,2,1) if len(data_1) == 3: d_gt, d_ngt, d_noi = data_1 elif len(data_1) == 2: d_gt, d_ngt = data_1 if len(data_1) == 3: ax.hist(d_noi, bins=50, color='k', alpha=0.5, label="Noise") ax.hist(d_ngt, bins=50, color='b', alpha=0.5, label="Non GT") ax.hist(d_gt, bins=75, color='r', alpha=0.5, label="GT") ax.grid(True) ax.set_title("Before") ax.set_ylabel("") ax.set_xlabel('# Samples') ax.set_xlabel('Distances') if len(data_2) == 3: d_gt, d_ngt, d_noi = data_2 elif len(data_2) == 2: d_gt, d_ngt = data_2 ax = fig.add_subplot(1,2,2) if len(data_2) == 3: ax.hist(d_noi, bins=50, color='k', alpha=0.5, label="Noise") ax.hist(d_ngt, bins=50, color='b', alpha=0.5, label="Non GT") ax.hist(d_gt, bins=75, color='r', alpha=0.5, label="GT") ax.grid(True) ax.set_title("After") ax.set_ylabel("") ax.set_xlabel('Distances') ax.legend() if save is None: pylab.show() else: pylab.savefig(save) pylab.close(fig) return