我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pylab.subplot()。
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 plot(self, ylim=None): import matplotlib.patches as mpatches import matplotlib.pyplot as plt from pylab import subplot number_of_subplots=len(self.scores.keys()) colors = ['blue', 'green', 'orange'] patches = [] for plot_idx, metric in enumerate(self.scores): for i, set_name in enumerate(self.scores[metric].keys()): data = self.scores[metric][set_name][0] time = self.scores[metric][set_name][1] patches.append(mpatches.Patch(color=colors[i], label='{0} {1}'.format(set_name, metric))) ax1 = subplot(number_of_subplots,1,plot_idx+1) ax1.plot(time,data, label='{0}'.format(metric), color=colors[i]) if ylim != None: plt.ylim(ymin=ylim[0]) plt.ylim(ymax=ylim[1]) plt.xlabel('iter') plt.ylabel('{0} {1}'.format(set_name, metric)) ax1.legend(handles=patches) plt.show()
def on_epoch_end(self, epoch, logs={}): self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % epoch)) self.show_edit_distance(256) word_batch = next(self.text_img_gen)[0] res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words]) for i in range(self.num_display_words): pylab.subplot(self.num_display_words, 1, i + 1) if K.image_dim_ordering() == 'th': the_input = word_batch['the_input'][i, 0, :, :] else: the_input = word_batch['the_input'][i, :, :, 0] pylab.imshow(the_input, cmap='Greys_r') pylab.xlabel('Truth = \'%s\' Decoded = \'%s\'' % (word_batch['source_str'][i], res[i])) fig = pylab.gcf() fig.set_size_inches(10, 12) pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % epoch)) pylab.close() # Input Parameters
def plot(self, overlay_alpha=0.5): import pylab as pl rows = int(sqrt(self.layers())) cols = int(ceil(self.layers()/rows)) for i in range(rows*cols): pl.subplot(rows, cols, i+1) pl.axis('off') if i >= self.layers(): continue pl.title('{}({})'.format(self.labels[i], i)) pl.imshow(self.image) pl.imshow(colorize(self.features[i].argmax(0), colors=np.array([[0, 0, 255], [0, 255, 255], [255, 255, 0], [255, 0, 0]])), alpha=overlay_alpha)
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 plot_okada(self, axes=None, dim=1, displacement='vertical', kwargs={}): if (self.dtopo is None): raise ValueError("Need to call create_dtopography before plot_okada") if (displacement is 'vertical'): if axes is None: from pylab import figure, subplot figure() axes = subplot(111) if (dim is 1): axes.plot(self.dtopo.x*LAT2METER,self.dtopo.dZ[0,0,:],**kwargs) elif (dim is 2): X,Y = numpy.meshgrid(self.dtopo.x,self.dtopo.y) axes.pcolormesh(X*LAT2METER,Y*LAT2METER,self.dtopo.dZ[0,:,:],**kwargs) elif (displacement is 'horizontal'): if axes is None: from pylab import figure, subplot figure() axes = subplot(111) if (dim is 1): axes.plot(self.dtopo.x*LAT2METER,self.dtopo.dY[0,0,:],**kwargs)
def plot_glcf_labelmap(labels, ax=None): import pylab as pl if ax is None: ax = pl.subplot(111) vimg = glcf_to_rgb(labels) vimg[labels.mask] = (0, 0, 0) ax.imshow(vimg, interpolation='nearest') lgd_patches = [] for glcf_type in sorted(np.unique(labels)): if glcf_type is ma.masked: continue lgd_patches.append( mpatches.Patch( color=np.array(CMAP[glcf_type]) / 255., label=CLASSES_NAMES[glcf_type] ) ) ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), handles=lgd_patches)
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 on_epoch_end(self, epoch, logs={}): self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch))) self.show_edit_distance(256) word_batch = next(self.text_img_gen)[0] res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words]) if word_batch['the_input'][0].shape[0] < 256: cols = 2 else: cols = 1 for i in range(self.num_display_words): pylab.subplot(self.num_display_words // cols, cols, i + 1) if K.image_dim_ordering() == 'th': the_input = word_batch['the_input'][i, 0, :, :] else: the_input = word_batch['the_input'][i, :, :, 0] pylab.imshow(the_input.T, cmap='Greys_r') pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i])) fig = pylab.gcf() fig.set_size_inches(10, 13) pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch))) pylab.close()
def tile_images(image_batch, image_width=28, image_height=28, image_channel=1, dir=None, filename="images"): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(16.0, 16.0) pylab.clf() pylab.gray() for m in range(100): pylab.subplot(10, 10, m + 1) pylab.imshow(image_batch[m].reshape((image_width, image_height)), interpolation="none") pylab.axis("off") pylab.savefig("{}/{}.png".format(dir, filename))
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_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 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 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 setMargins(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None): """ Tune the subplot layout via the meanings (and suggested defaults) are:: left = 0.125 # the left side of the subplots of the figure right = 0.9 # the right side of the subplots of the figure bottom = 0.1 # the bottom of the subplots of the figure top = 0.9 # the top of the subplots of the figure wspace = 0.2 # the amount of width reserved for blank space between subplots hspace = 0.2 # the amount of height reserved for white space between subplots The actual defaults are controlled by the rc file """ plt.subplots_adjust(left, bottom, right, top, wspace, hspace) plt.draw_if_interactive()
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 plot_eigenspectrum(G, s, nvis, nhid): with misc.gnumpy_conversion_check('allow'): dim = G.shape[0] d, Q = scipy.linalg.eigh(G) d = d[::-1] Q = Q[:, ::-1] pts = np.unique(np.floor(np.logspace(0., np.log10(dim-1), 500)).astype(int)) - 1 cf = [fisher.correlation_fraction(Q[:, i], s, nvis, nhid) for i in pts] pylab.figure() pylab.subplot(2, 1, 1) pylab.loglog(range(1, dim+1), d, 'b-', lw=2.) pylab.xticks([]) pylab.yticks(fontsize='large') pylab.subplot(2, 1, 2) pylab.semilogx(pts+1, cf, 'r-', lw=2.) pylab.xticks(fontsize='x-large') pylab.yticks(fontsize='large')
def two_plot_time_freq_mag(self, minlen=10): part = [pp for pp in self.partial if len(pp.f) > minlen] pl.figure() ax1 = pl.subplot(211) pl.hold(True) ax2 = pl.subplot(212, sharex=ax1) pl.hold(True) for pp in part: ax1.plot(pp.start_idx + np.arange(len(pp.f)), np.array(pp.f)) ax2.plot(pp.start_idx + np.arange(len(pp.f)), 20*np.log10(np.array(pp.mag))) ax1.hold(False) # ax1.xlabel('Time (s)') ax1.set_ylabel('Frequency (Hz)') ax2.set_xlabel('Time (s)') ax2.set_ylabel('Frequency (Hz)') # pl.show() return pl.gca()
def tile_binary_images(x, dir=None, filename="x", row=10, col=10): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(col * 2, row * 2) pylab.clf() pylab.gray() for m in range(row * col): pylab.subplot(row, col, m + 1) pylab.imshow(np.clip(x[m], 0, 1), interpolation="none") pylab.axis("off") pylab.savefig("{}/{}.png".format(dir, filename))
def plotstuff(): X__ = np.load("tm_X.npy") S_pred = np.load("tm_S_pred.npy") E_pred = np.load("tm_E_pred.npy") M = np.load("tm_M.npy") pl.ioff() pl.suptitle("mode: %s (X: FM input, state pred: FM output)" % ("bluib")) pl.subplot(511) pl.title("X[goals]") pl.plot(X__[10:,0:4], "-x") pl.subplot(512) pl.title("X[prediction error]") pl.plot(X__[10:,4:], "-x") pl.subplot(513) pl.title("state pred") pl.plot(S_pred) pl.subplot(514) pl.title("error state - goal") pl.plot(E_pred) pl.subplot(515) pl.title("state") pl.plot(M) pl.show()
def tile_binary_images(x, dir=None, filename="x"): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(16.0, 16.0) pylab.clf() pylab.gray() for m in range(100): pylab.subplot(10, 10, m + 1) pylab.imshow(np.clip(x[m], 0, 1), interpolation="none") pylab.axis("off") pylab.savefig("{}/{}.png".format(dir, filename))
def plot_multiple_rocs_separate(rocList,title='', labels = None, equal_aspect = True): """ Plot multiples ROC curves as separate at the same painting area. """ pylab.clf() pylab.title(title) for ix, r in enumerate(rocList): ax = pylab.subplot(4,4,ix+1) pylab.ylim((0,1)) pylab.xlim((0,1)) ax.set_yticklabels([]) ax.set_xticklabels([]) if equal_aspect: cax = pylab.gca() cax.set_aspect('equal') if not labels: labels = ['' for x in rocList] pylab.text(0.2,0.1,labels[ix],fontsize=8) pylab.plot([x[0] for x in r.derived_points],[y[1] for y in r.derived_points], 'r-',linewidth=2) pylab.show()
def plot_signals(input_data, filename=None,downsamplefactor=1,n_columns=1): import pylab as pl n_rows = input_data.signal.n_channels() n_rows = int(n_rows/n_columns) print str(n_rows) + ' ' + str(n_columns) for row in range(n_rows): for col in range(n_columns): print (row)*n_columns+col+1 pl.subplot(n_rows, n_columns, row*n_columns+col+1) if downsamplefactor==1: pl.plot(input_data.timebase, input_data.signal.get_channel(row*n_columns+col)) pl.axis([-0.01,0.1,-5, 5]) else: plotdata=input_data.signal.get_channel(row*n_columns+col) timedata=input_data.timebase pl.plot(timedata[0:len(timedata):downsamplefactor], plotdata[0:len(timedata):downsamplefactor]) pl.axis([-0.01,0.1,-5,5]) if filename != None: pl.savefig(filename) else: pl.show()
def visualize_x(reconstructed_x_batch, image_width=28, image_height=28, image_channel=1, dir=None): if dir is None: raise Exception() try: os.mkdir(dir) except: pass fig = pylab.gcf() fig.set_size_inches(16.0, 16.0) pylab.clf() if image_channel == 1: pylab.gray() for m in range(100): pylab.subplot(10, 10, m + 1) if image_channel == 1: pylab.imshow(reconstructed_x_batch[m].reshape((image_width, image_height)), interpolation="none") elif image_channel == 3: pylab.imshow(reconstructed_x_batch[m].reshape((image_channel, image_width, image_height)), interpolation="none") pylab.axis("off") pylab.savefig("%s/reconstructed_x.png" % dir)
def visualize_labeled_z(z_batch, label_batch, dir=None): fig = pylab.gcf() fig.set_size_inches(20.0, 16.0) pylab.clf() colors = ["#2103c8", "#0e960e", "#e40402","#05aaa8","#ac02ab","#aba808","#151515","#94a169", "#bec9cd", "#6a6551"] for n in xrange(z_batch.shape[0]): result = pylab.scatter(z_batch[n, 0], z_batch[n, 1], c=colors[label_batch[n]], s=40, marker="o", edgecolors='none') classes = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] recs = [] for i in range(0, len(colors)): recs.append(mpatches.Rectangle((0, 0), 1, 1, fc=colors[i])) ax = pylab.subplot(111) box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) ax.legend(recs, classes, loc="center left", bbox_to_anchor=(1.1, 0.5)) pylab.xticks(pylab.arange(-4, 5)) pylab.yticks(pylab.arange(-4, 5)) pylab.xlabel("z1") pylab.ylabel("z2") pylab.savefig("%s/labeled_z.png" % dir)
def removeIllumination2(self, size, title = ''): out = ndimage.filters.gaussian_filter(self.image, size) pylab.figure() pylab.subplot(2,2,1) pylab.axis('off') pylab.imshow(self.image) pylab.subplot(2,2,2) pylab.axis('off') pylab.imshow(out) pylab.subplot(2,2,3) pylab.axis('off') pylab.imshow(self.image - out) pylab.subplot(2,2,4) pylab.axis('off') pylab.imshow(self.smooth - out) if title != '': pylab.savefig(title) pylab.close() else: pylab.show() self.smooth -= out return self.image - out
def plot(self, outpath=''): pylab.figure(figsize = (17,10)) diff = self.f2-self.f3 pylab.subplot(2,1,1) pylab.plot(range(self.lengthSeq), self.f2, 'r-', label = "f2") pylab.plot(range(self.lengthSeq), self.f3, 'g-', label = "f3") pylab.xlim([0., self.lengthSeq]) pylab.tick_params(axis='both', which='major', labelsize=25) pylab.subplot(2,1,2) diff2 = diff/self.f3 diff2 /= np.max(diff2) pylab.plot(range(self.lengthSeq), diff2, 'b-', label = "Rescaled (by max) difference / f3") pylab.xlabel("Temps (en images)", fontsize = 25) pylab.tick_params(axis='both', which='major', labelsize=25) pylab.xlim([0., self.lengthSeq]) #pylab.legend(loc= 2, prop = {'size':15}) pylab.savefig(outpath) pylab.close()
def plotAgainstGFP_hist2d(self): fig1 = pylab.figure(figsize = (20, 15)) print len(self.GFP) for i in xrange(min(len(data.cat), 4)): print len(self.GFP[self.categories == i]) vect = [] pylab.subplot(2,2,i+1) pop = self.GFP[self.categories == i] print "cat", i, "n pop", len(self.GFP[(self.categories == i) & (self.GFP > -np.log(12.5))]) H, xedges, yedges = np.histogram2d(self.angles[self.categories == i], self.GFP[self.categories == i], bins = 10) hist = pylab.hist2d(self.GFP[self.categories == i], self.angles[self.categories == i], bins = 10, cmap = pylab.cm.Reds, normed = True) pylab.clim(0.,0.035) pylab.colorbar() pylab.title(data.cat[i]) pylab.xlabel('GFP score') pylab.ylabel('Angle (degree)') pylab.xlim([-4.2, -1]) pylab.show()
def bootstrap_extradata(self, nBoot, extradataA, nbins = 20): pops =[] meanpop = [[] for i in data.cat] pylab.figure(figsize = (14,14)) for i in xrange(min(4, len(extradataA))): #pylab.subplot(2,2,i+1) if i ==0: pylab.title("Bootstrap on means", fontsize = 20.) pop = extradataA[i]# & (self.GFP > 2000)]# for index in xrange(nBoot): newpop = np.random.choice(pop, size=len(pop), replace=True) #meanpop[i].append(np.mean(newpop)) pops.append(newpop) pylab.legend() #pylab.title(cat[i]) pylab.xlabel("Angle(degree)", fontsize = 15) pylab.xlim([0., 90.]) for i in xrange(len(extradataA)): for j in xrange(i+1, len(extradataA)): statT, pvalue = scipy.stats.ttest_ind(pops[i], pops[j], equal_var=False) print "cat{0} & cat{1} get {2} ({3})".format(i,j, pvalue,statT) pylab.savefig("/users/biocomp/frose/frose/Graphics/FINALRESULTS-diff-f3/mean_nBootstrap{0}_bins{1}_GFPsup{2}_FLO_{3}.png".format(nBoot, nbins, 'all', randint(0,999)))
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_performance(file_name, triggers, lims=(150,150)): params = CircusParser(file_name) N_e = params.getint('data', 'N_e') N_total = params.getint('data', 'N_total') sampling_rate = params.getint('data', 'sampling_rate') do_temporal_whitening = params.getboolean('whitening', 'temporal') do_spatial_whitening = params.getboolean('whitening', 'spatial') spike_thresh = params.getfloat('detection', 'spike_thresh') file_out_suff = params.get('data', 'file_out_suff') N_t = params.getint('detection', 'N_t') nodes, edges = get_nodes_and_edges(params) chunk_size = N_t if do_spatial_whitening: spatial_whitening = load_data(params, 'spatial_whitening') if do_temporal_whitening: temporal_whitening = load_data(params, 'temporal_whitening') thresholds = load_data(params, 'thresholds') try: result = load_data(params, 'results') except Exception: result = {'spiketimes' : {}, 'amplitudes' : {}} curve = numpy.zeros((len(triggers), len(result['spiketimes'].keys()), lims[1]+lims[0]), dtype=numpy.int32) count = 0 for count, t_spike in enumerate(triggers): for key in result['spiketimes'].keys(): elec = int(key.split('_')[1]) idx = numpy.where((result['spiketimes'][key] > t_spike - lims[0]) & (result['spiketimes'][key] < t_spike + lims[0])) curve[count, elec, t_spike - result['spiketimes'][key][idx]] += 1 pylab.subplot(111) pylab.imshow(numpy.mean(curve, 0), aspect='auto') return curve
def view_raw_templates(file_name, n_temp=2, square=True): N_e, N_t, N_tm = templates.shape if not numpy.iterable(n_temp): if square: idx = numpy.random.permutation(numpy.arange(N_tm//2))[:n_temp**2] else: idx = numpy.random.permutation(numpy.arange(N_tm//2))[:n_temp] else: idx = n_temp import matplotlib.colors as colors my_cmap = pylab.get_cmap('winter') cNorm = colors.Normalize(vmin=0, vmax=N_e) scalarMap = pylab.cm.ScalarMappable(norm=cNorm, cmap=my_cmap) pylab.figure() for count, i in enumerate(idx): if square: pylab.subplot(n_temp, n_temp, count + 1) if (numpy.mod(count, n_temp) != 0): pylab.setp(pylab.gca(), yticks=[]) if (count < n_temp*(n_temp - 1)): pylab.setp(pylab.gca(), xticks=[]) else: pylab.subplot(len(idx), 1, count + 1) if count != (len(idx) - 1): pylab.setp(pylab.gca(), xticks=[]) for j in xrange(N_e): colorVal = scalarMap.to_rgba(j) pylab.plot(templates[j, :, i], color=colorVal) pylab.title('Template %d' %i) pylab.tight_layout() pylab.show()
def get_performance(file_name, name): a, b = os.path.splitext(os.path.basename(file_name)) file_name, ext = os.path.splitext(file_name) file_out = os.path.join(os.path.abspath(file_name), a) data = {} result = h5py.File(file_out + '.basis.hdf5') data['spatial'] = result.get('spatial')[:] data['temporal'] = numpy.zeros(61) #result.get('temporal')[:] pylab.figure() pylab.subplot(121) pylab.imshow(data['spatial'], interpolation='nearest') pylab.title('Spatial') pylab.xlabel('# Electrode') pylab.ylabel('# Electrode') pylab.colorbar() pylab.subplot(122) pylab.title('Temporal') pylab.plot(data['temporal']) pylab.xlabel('Time [ms]') x, y = pylab.xticks() pylab.xticks(x, (x-x[-1]//2)//10) pylab.tight_layout() plot_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '.')) plot_path = os.path.join(plot_path, 'plots') plot_path = os.path.join(plot_path, 'whitening') if not os.path.exists(plot_path): os.makedirs(plot_path) output = os.path.join(plot_path, '%s.pdf' %name) pylab.savefig(output) return data
def align_subplots( N, M, xlim=None, ylim=None, ): """make all of the subplots have the same limits, turn off unnecessary ticks""" # find sensible xlim,ylim if xlim is None: xlim = [np.inf, -np.inf] for i in range(N * M): pb.subplot(N, M, i + 1) xlim[0] = min(xlim[0], pb.xlim()[0]) xlim[1] = max(xlim[1], pb.xlim()[1]) if ylim is None: ylim = [np.inf, -np.inf] for i in range(N * M): pb.subplot(N, M, i + 1) ylim[0] = min(ylim[0], pb.ylim()[0]) ylim[1] = max(ylim[1], pb.ylim()[1]) for i in range(N * M): pb.subplot(N, M, i + 1) pb.xlim(xlim) pb.ylim(ylim) if i % M: pb.yticks([]) else: removeRightTicks() if i < M * (N - 1): pb.xticks([]) else: removeUpperTicks()
def plotgrid(data,d=10,shape=(30,30)): """Plot a list of images on a grid.""" ion() gray() clf() for i in range(min(d*d,len(data))): subplot(d,d,i+1) row = data[i] if shape is not None: row = row.reshape(shape) imshow(row) ginput(1,timeout=0.1)
def showgrid(l,cols=None,n=400,titles=None,xlabels=None,ylabels=None,**kw): if "cmap" not in kw: kw["cmap"] = cm.gray if "interpolation" not in kw: kw["interpolation"] = "nearest" n = minimum(n,len(l)) if cols is None: cols = int(sqrt(n)) rows = (n+cols-1)//cols for i in range(n): pylab.xticks([]) ;pylab.yticks([]) pylab.subplot(rows,cols,i+1) pylab.imshow(l[i],**kw) if titles is not None: pylab.title(str(titles[i])) if xlabels is not None: pylab.xlabel(str(xlabels[i])) if ylabels is not None: pylab.ylabel(str(ylabels[i]))
def resetplot(): import matplotlib import pylab as plt kw = {} for p in ['bottom', 'top', 'left', 'right', 'hspace', 'wspace']: kw[p] = matplotlib.rcParams['figure.subplot.' + p] plt.subplots_adjust(**kw)
def plotaffinegrid(affines, exag=1e3, affineOnly=True, R=0.025, tpre='', bboxes=None): import pylab as plt NR = 3 NC = int(ceil(len(affines)/3.)) #R = 0.025 # 1.5 arcmin #for (exag,affonly) in [(1e2, False), (1e3, True), (1e4, True)]: plt.clf() for i,aff in enumerate(affines): plt.subplot(NR, NC, i+1) dl = aff.refdec - R dh = aff.refdec + R rl = aff.refra - R / aff.rascale rh = aff.refra + R / aff.rascale RR,DD = np.meshgrid(np.linspace(rl, rh, 11), np.linspace(dl, dh, 11)) plotaffine(aff, RR.ravel(), DD.ravel(), exag=exag, affineOnly=affineOnly, doclf=False, units='dots', width=2, headwidth=2.5, headlength=3, headaxislength=3) if bboxes is not None: for bb in bboxes: plt.plot(*bb, linestyle='-', color='0.5') plt.plot(*bboxes[i], linestyle='-', color='k') setRadecAxes(rl,rh,dl,dh) plt.xlabel('') plt.ylabel('') plt.xticks([]) plt.yticks([]) plt.title('field %i' % (i+1)) plt.subplots_adjust(left=0.05, right=0.95, wspace=0.1) if affineOnly: tt = tpre + 'Affine part of transformations' else: tt = tpre + 'Transformations' plt.suptitle(tt + ' (x %g)' % exag)
def plot_facade_cuts(self): facade_sig = self.facade_edge_scores.sum(0) facade_cuts = find_facade_cuts(facade_sig, dilation_amount=self.facade_merge_amount) mu = np.mean(facade_sig) sigma = np.std(facade_sig) w = self.rectified.shape[1] pad=10 gs1 = pl.GridSpec(5, 5) gs1.update(wspace=0.5, hspace=0.0) # set the spacing between axes. pl.subplot(gs1[:3, :]) pl.imshow(self.rectified) pl.vlines(facade_cuts, *pl.ylim(), lw=2, color='black') pl.axis('off') pl.xlim(-pad, w+pad) pl.subplot(gs1[3:, :], sharex=pl.gca()) pl.fill_between(np.arange(w), 0, facade_sig, lw=0, color='red') pl.fill_between(np.arange(w), 0, np.clip(facade_sig, 0, mu+sigma), color='blue') pl.plot(np.arange(w), facade_sig, color='blue') pl.vlines(facade_cuts, facade_sig[facade_cuts], pl.xlim()[1], lw=2, color='black') pl.scatter(facade_cuts, facade_sig[facade_cuts]) pl.axis('off') pl.hlines(mu, 0, w, linestyle='dashed', color='black') pl.text(0, mu, '$\mu$ ', ha='right') pl.hlines(mu + sigma, 0, w, linestyle='dashed', color='gray',) pl.text(0, mu + sigma, '$\mu+\sigma$ ', ha='right') pl.xlim(-pad, w+pad)
def on_epoch_end(self, epoch, logs={}): self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch))) self.show_edit_distance(256) word_batch = next(self.text_img_gen)[0] res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words]) if word_batch['the_input'][0].shape[0] < 256: cols = 2 else: cols = 1 for i in range(self.num_display_words): pylab.subplot(self.num_display_words // cols, cols, i + 1) if K.image_data_format() == 'channels_first': the_input = word_batch['the_input'][i, 0, :, :] else: the_input = word_batch['the_input'][i, :, :, 0] pylab.imshow(the_input.T, cmap='Greys_r') pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i])) fig = pylab.gcf() fig.set_size_inches(10, 13) pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch))) pylab.close()
def plot(self): ''' This is a wrapper function to generate the complete sag plot. It requires datasets with two keys, 'data' and 'heading'. The former should contain all necessary information (as a subdictionary) to call all the _draw* functions. ''' plot_colours = ('r', 'b', 'g', 'y') f, axes = plt.subplots(3, 1, figsize=(16,7)) ax = plt.subplot(1, 4, 1) plt.tick_params(labelsize=10) plt.rcParams.update({'axes.titlesize': 'small', 'axes.labelsize': 'small', 'xtick.labelsize':'small', 'ytick.labelsize':'small'}) for idx, d in enumerate(self.datasets): self._drawLinearDisplacementsToAxis(ax, d['data']['x'], d['data']['y'], d['data']['x_err'], d['data']['y_err'], d['data']['mount_angles'], d['data']['fit_xc'], d['data']['fit_yc'], d['data']['fit_r'], d['heading'], color=plot_colours[idx]) ax = plt.subplot(1, 4, 2, projection='polar') for idx, d in enumerate(self.datasets): self._drawRadialDisplacementsToAxis(ax, d['data']['xy_angles_from_12_o_clock'], (d['data']['x'], d['data']['y']), d['data']['mount_angles'], label=d['heading'], color=plot_colours[idx]) ax = plt.subplot(1, 4, 3, projection='polar') for idx, d in enumerate(self.datasets): self._drawResidualsToAxis(ax, d['data']['xy_angles_from_12_o_clock'], d['data']['residuals'], d['data']['mount_angles'], label=d['heading'], color=plot_colours[idx]) ax = plt.subplot(1, 4, 4, projection='polar') for idx, d in enumerate(self.datasets): self._drawAnglesFromMountNormalToAxis(ax, d['data']['xy_angles_from_12_o_clock'], [angle[2] for angle in d['data']['angles_from_mount_normal']], d['data']['mount_angles'], label=d['heading'], color=plot_colours[idx])
def plot_trajectories(self): pylab.clf() pylab.rc('text', usetex=True) pylab.rc('font', size=18) pylab.subplot(121) self.plot_com() pylab.subplot(122) self.plot_zmp()
def test_discretization(nmpc, nb_steps): dT = nmpc.preview.dT pylab.ion() pylab.clf() ax = pylab.subplot(311) ax.set_color_cycle(['r', 'g', 'b']) pylab.plot( [sum(dT[:i]) for i in xrange(len(dT))], nmpc.preview.P, marker='o') pylab.plot( pylab.linspace(0., sum(dT), nb_steps + 1), [x[0:3] for x in nmpc.preview.discretize(nb_steps)], marker='s', linestyle='--') ax = pylab.subplot(312) ax.set_color_cycle(['r', 'g', 'b']) pylab.plot( [sum(dT[:i]) for i in xrange(len(dT))], nmpc.preview.V, marker='o') pylab.plot( pylab.linspace(0., sum(dT), nb_steps + 1), [x[3:6] for x in nmpc.preview.discretize(nb_steps)], marker='s', linestyle='--') ax = pylab.subplot(313) ax.set_color_cycle(['r', 'g', 'b']) pylab.plot( [sum(dT[:i]) for i in xrange(len(dT))], nmpc.preview.Z, marker='o') pylab.plot( pylab.linspace(0., sum(dT), nb_steps + 1), [x[6:9] for x in nmpc.preview.discretize(nb_steps)], marker='s', linestyle='--')