Python pylab.clf() Examples
The following are 30
code examples of pylab.clf().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
pylab
, or try the search function
.
Example #1
Source File: plots.py From ColorPy with GNU Lesser General Public License v2.1 | 6 votes |
def scattered_visual_brightness (): '''Plot the perceptual brightness of Rayleigh scattered light.''' # get 'spectra' for y matching functions and multiply by 1/wl^4 spectrum_y = ciexyz.empty_spectrum() (num_wl, num_cols) = spectrum_y.shape for i in range (0, num_wl): wl_nm = spectrum_y [i][0] rayleigh = math.pow (550.0 / wl_nm, 4) xyz = ciexyz.xyz_from_wavelength (wl_nm) spectrum_y [i][1] = xyz [1] * rayleigh pylab.clf () pylab.title ('Perceptual Brightness of Rayleigh Scattered Light') pylab.xlabel ('Wavelength (nm)') pylab.ylabel ('CIE $Y$ / $\lambda^4$') spectrum_subplot (spectrum_y) tighten_x_axis (spectrum_y [:,0]) # done filename = 'Visual_scattering' print ('Saving plot %s' % str (filename)) pylab.savefig (filename)
Example #2
Source File: fitter.py From fitter with GNU General Public License v3.0 | 6 votes |
def summary(self, Nbest=5, lw=2, plot=True, method="sumsquare_error"): """Plots the distribution of the data and Nbest distribution """ if plot: pylab.clf() self.hist() self.plot_pdf(Nbest=Nbest, lw=lw, method=method) pylab.grid(True) Nbest = min(Nbest, len(self.distributions)) try: names = self.df_errors.sort_values( by=method).index[0:Nbest] except: names = self.df_errors.sort(method).index[0:Nbest] return self.df_errors.loc[names]
Example #3
Source File: doscalars.py From pysynphot with BSD 3-Clause "New" or "Revised" License | 6 votes |
def plotdata(obsmode,spectrum,val,odict,sdict, instr,fieldname,outdir,outname): isetting=P.isinteractive() P.ioff() P.clf() P.plot(obsmode,val,'.') P.ylabel('(pysyn-syn)/syn') P.xlabel('obsmode') P.title("%s: %s"%(instr,fieldname)) P.savefig(os.path.join(outdir,outname+'_obsmode.ps')) P.clf() P.plot(spectrum,val,'.') P.ylabel('(pysyn-syn)/syn') P.xlabel('spectrum') P.title("%s: %s"%(instr,fieldname)) P.savefig(os.path.join(outdir,outname+'_spectrum.ps')) matplotlib.interactive(isetting)
Example #4
Source File: functional_map.py From cmm with GNU General Public License v2.0 | 6 votes |
def plot_functional_map(C, newfig=True): vmax = max(np.abs(C.max()), np.abs(C.min())) vmin = -vmax C = ((C - vmin) / (vmax - vmin)) * 2 - 1 if newfig: pl.figure(figsize=(5,5)) else: pl.clf() ax = pl.gca() pl.pcolor(C[::-1], edgecolor=(0.9, 0.9, 0.9, 1), lw=0.5, vmin=-1, vmax=1, cmap=nice_mpl_color_map()) # colorbar tick_locs = [-1., 0.0, 1.0] tick_labels = ['min', 0, 'max'] bar = pl.colorbar() bar.locator = matplotlib.ticker.FixedLocator(tick_locs) bar.formatter = matplotlib.ticker.FixedFormatter(tick_labels) bar.update_ticks() ax.set_aspect(1) pl.xticks([]) pl.yticks([]) if newfig: pl.show()
Example #5
Source File: experiment.py From double-dqn with MIT License | 6 votes |
def plot_evaluation_episode_reward(): pylab.clf() sns.set_context("poster") pylab.plot(0, 0) episodes = [0] average_scores = [0] median_scores = [0] for n in xrange(len(csv_evaluation)): params = csv_evaluation[n] episodes.append(params[0]) average_scores.append(params[1]) median_scores.append(params[2]) pylab.plot(episodes, average_scores, sns.xkcd_rgb["windows blue"], lw=2) pylab.xlabel("episodes") pylab.ylabel("average score") pylab.savefig("%s/evaluation_episode_average_reward.png" % args.plot_dir) pylab.clf() pylab.plot(0, 0) pylab.plot(episodes, median_scores, sns.xkcd_rgb["windows blue"], lw=2) pylab.xlabel("episodes") pylab.ylabel("median score") pylab.savefig("%s/evaluation_episode_median_reward.png" % args.plot_dir)
Example #6
Source File: dataset_finesse.py From DEMUD with Apache License 2.0 | 5 votes |
def plot_item(self, m, ind, x, r, k, label): """plot_item(self, m, ind, x, r, k, label) Plot selection m (index ind, data in x) and its reconstruction r, with k and label to annotate of the plot. """ if x == [] or r == []: print "Error: No data in x and/or r." return pylab.clf() # xvals, x, and r need to be column vectors pylab.plot(self.xvals, r, color='0.6', label='Expected') # Color code: # positive residuals = red # negative residuals = blue pylab.plot(self.xvals, x, color='0.0', label='Observed') posres = np.where((x-r) > 0)[0] negres = np.where((x-r) < 0)[0] pylab.plot(self.xvals[posres], x[posres], 'r.', markersize=3, label='Higher') pylab.plot(self.xvals[negres], x[negres], 'b.', markersize=3, label='Lower') pylab.xlabel(self.xlabel) pylab.ylabel(self.ylabel) pylab.title('DEMUD selection %d (%s), item %d, using K=%d' % \ (m, label, ind, k)) pylab.legend() #fontsize=10) outdir = os.path.join('results', self.name) if not os.path.exists(outdir): os.mkdir(outdir) figfile = os.path.join(outdir, 'sel-%d-k-%d-(%s).png' % (m, k, label)) pylab.savefig(figfile) print 'Wrote plot to %s' % figfile pylab.close()
Example #7
Source File: celllab_cts.py From landlab with MIT License | 5 votes |
def update_plot(self): """Plot the current node state grid.""" plt.clf() if self.gridtype == "rast": nsr = self.ca.grid.node_vector_to_raster(self.ca.node_state) plt.imshow(nsr, interpolation="None", origin="lower", cmap=self._cmap) else: self.ca.grid.hexplot(self.ca.node_state, color_map=self._cmap) plt.draw() plt.pause(0.001)
Example #8
Source File: dataset_float_classes.py From DEMUD with Apache License 2.0 | 5 votes |
def plot_item(self, m, ind, x, r, k, label, U, rerr, feature_weights): if x == [] or r == []: print "Error: No data in x and/or r." return pylab.clf() # xvals, x, and r need to be column vectors # xvals represent bin end points, so we need to duplicate most of them x = np.repeat(x, 2, axis=0) r = np.repeat(r, 2, axis=0) pylab.subplot(2,1,1) pylab.semilogx(self.xvals, r[0:128], 'r-', label='Expected') pylab.semilogx(self.xvals, x[0:128], 'b.-', label='Observations') pylab.xlabel('CTN: ' + self.xlabel) pylab.ylabel(self.ylabel) pylab.legend(loc='upper left', fontsize=10) pylab.subplot(2,1,2) pylab.semilogx(self.xvals, r[128:], 'r-', label='Expected') pylab.semilogx(self.xvals, x[128:], 'b.-', label='Observations') pylab.xlabel('CETN: ' + self.xlabel) pylab.ylabel(self.ylabel) pylab.legend(loc='upper left', fontsize=10) pylab.suptitle('DEMUD selection %d (%s), item %d, using K=%d' % \ (m, label, ind, k)) outdir = os.path.join('results', self.name) if not os.path.exists(outdir): os.mkdir(outdir) figfile = os.path.join(outdir, 'sel-%d-k-%d-(%s).pdf' % (m, k, label)) pylab.savefig(figfile) print 'Wrote plot to %s' % figfile pylab.close()
Example #9
Source File: sound.py From multisensory with Apache License 2.0 | 5 votes |
def test_spectrogram(): # http://matplotlib.org/examples/pylab_examples/specgram_demo.html dt = 1./0.0005 t = np.arange(0., 20., dt) #t = np.arange(0., 3., dt) s1 = np.sin((2*np.pi)*100*t) s2 = 2 * np.sin((2*np.pi)*400*t) s2[-((10 < t) & (t < 12))] = 0 nse = 0.01 * np.random.randn(len(t)) if 0: x = s1 else: x = s1 + s2 + nse freqs, spec, spec_times = make_specgram(x, dt) pl.clf() ax1 = pl.subplot(211) ax1.plot(t, x) if 1: lsp = spec.copy() lsp[spec > 0] = np.log(spec[spec > 0]) lsp = ut.clip_rescale(lsp, -10, np.percentile(lsp, 99)) else: lsp = spec.copy() lsp = ut.clip_rescale(lsp, 0, np.percentile(lsp, 99)) ax2 = pl.subplot(212, sharex = ax1) ax2.imshow(lsp.T, cmap = pl.cm.jet, extent = (0., t[-1], np.min(freqs), np.max(freqs)), aspect = 'auto') ig.show(vis_specgram(freqs, spec, spec_times)) ut.toplevel_locals()
Example #10
Source File: generate_figs.py From discrete_sieve with Apache License 2.0 | 5 votes |
def stack_digit(zs, filename): pylab.clf() fig = pylab.figure(frameon=False) fig.set_size_inches(1, 3) ax = pylab.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) ax.imshow(np.vstack(zs).reshape((-1, 28)), interpolation='nearest', cmap=pylab.cm.gray) fig.savefig('results/' + filename + '.pdf') pylab.close('all')
Example #11
Source File: plots.py From ColorPy with GNU Lesser General Public License v2.1 | 5 votes |
def cie_matching_functions_plot (): '''Plot the CIE XYZ matching functions, as three spectral subplots.''' # get 'spectra' for x,y,z matching functions spectrum_x = ciexyz.empty_spectrum() spectrum_y = ciexyz.empty_spectrum() spectrum_z = ciexyz.empty_spectrum() (num_wl, num_cols) = spectrum_x.shape for i in range (0, num_wl): wl_nm = spectrum_x [i][0] xyz = ciexyz.xyz_from_wavelength (wl_nm) spectrum_x [i][1] = xyz [0] spectrum_y [i][1] = xyz [1] spectrum_z [i][1] = xyz [2] # Plot three separate subplots, with CIE X in the first, CIE Y in the second, and CIE Z in the third. # Label appropriately for the whole plot. pylab.clf () # X pylab.subplot (3,1,1) pylab.title ('1931 CIE XYZ Matching Functions') pylab.ylabel ('CIE $X$') spectrum_subplot (spectrum_x) tighten_x_axis (spectrum_x [:,0]) # Y pylab.subplot (3,1,2) pylab.ylabel ('CIE $Y$') spectrum_subplot (spectrum_y) tighten_x_axis (spectrum_x [:,0]) # Z pylab.subplot (3,1,3) pylab.xlabel ('Wavelength (nm)') pylab.ylabel ('CIE $Z$') spectrum_subplot (spectrum_z) tighten_x_axis (spectrum_x [:,0]) # done filename = 'CIEXYZ_Matching' print ('Saving plot %s' % str (filename)) pylab.savefig (filename)
Example #12
Source File: plots.py From ColorPy with GNU Lesser General Public License v2.1 | 5 votes |
def rgb_patch_plot ( rgb_colors, color_names, title, filename, patch_gap = 0.05, num_across = 6): '''Draw a set of color patches, specified as linear rgb colors.''' def draw_patch (x0, y0, color, name, patch_gap): '''Draw a patch of color.''' # patch relative vertices m = patch_gap omm = 1.0 - m poly_dx = [m, m, omm, omm] poly_dy = [m, omm, omm, m] # construct vertices poly_x = [ x0 + dx_i for dx_i in poly_dx ] poly_y = [ y0 + dy_i for dy_i in poly_dy ] pylab.fill (poly_x, poly_y, color) if name != None: dtext = 0.1 pylab.text (x0+dtext, y0+dtext, name, size=8.0) # make plot with each color with one patch pylab.clf() num_colors = len (rgb_colors) for i in range (0, num_colors): (iy, ix) = divmod (i, num_across) # get color as a displayable string colorstring = colormodels.irgb_string_from_rgb (rgb_colors [i]) if color_names != None: name = color_names [i] else: name = None draw_patch (float (ix), float (-iy), colorstring, name, patch_gap) pylab.axis ('off') pylab.title (title) print ('Saving plot %s' % str (filename)) pylab.savefig (filename)
Example #13
Source File: visualize.py From pathnet-pytorch with BSD 3-Clause "New" or "Revised" License | 5 votes |
def show(self, genes, color): if self.vis: self.get_fig(genes, color) pylab.draw() pause(0.05) pylab.clf() self.reset()
Example #14
Source File: visu_classification.py From JDOT with MIT License | 5 votes |
def predict_test_grid(clf,gamma,Xapp): return predict_test(clf,gamma,Xapp,xfin).reshape((xx.shape[0],xx.shape[1],3)) #%% plot data
Example #15
Source File: plotting.py From webvectors with GNU General Public License v3.0 | 5 votes |
def singularplot(word, modelname, vector, fname): xlocations = np.array(list(range(len(vector)))) plot.clf() plot.bar(xlocations, vector) plot_title = word.split('_')[0].replace('::', ' ') + '\n' + modelname + u' model' plot.title(plot_title, fontproperties=font) plot.xlabel('Vector components') plot.ylabel('Components values') plot.savefig(root + 'data/images/singleplots/' + modelname + '_' + fname + '.png', dpi=150, bbox_inches='tight') plot.close() plot.clf()
Example #16
Source File: visu_classification.py From JDOT with MIT License | 5 votes |
def predict_test(clf,gamma,Xapp,Xtest): Kx=classif.rbf_kernel(Xtest,Xapp,gamma=gamma) return clf.predict(Kx)
Example #17
Source File: TensorFlowInterface.py From IntroToDeepLearning with MIT License | 5 votes |
def plotFields(layer,fieldShape=None,channel=None,figOffset=1,cmap=None,padding=0.01): # Receptive Fields Summary try: W = layer.W except: W = layer wp = W.eval().transpose(); if len(np.shape(wp)) < 4: # Fully connected layer, has no shape fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape) else: # Convolutional layer already has shape features, channels, iy, ix = np.shape(wp) if channel is not None: fields = wp[:,channel,:,:] else: fields = np.reshape(wp,[features*channels,iy,ix]) perRow = int(math.floor(math.sqrt(fields.shape[0]))) perColumn = int(math.ceil(fields.shape[0]/float(perRow))) fig = mpl.figure(figOffset); mpl.clf() # Using image grid from mpl_toolkits.axes_grid1 import ImageGrid grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single') for i in range(0,np.shape(fields)[0]): im = grid[i].imshow(fields[i],cmap=cmap); grid.cbar_axes[0].colorbar(im) mpl.title('%s Receptive Fields' % layer.name) # old way # fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))]) # tiled = [] # for i in range(0,perColumn*perRow,perColumn): # tiled.append(np.hstack(fields2[i:i+perColumn])) # # tiled = np.vstack(tiled) # mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar(); mpl.figure(figOffset+1); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar()
Example #18
Source File: plotting.py From webvectors with GNU General Public License v3.0 | 5 votes |
def embed(words, matrix, classes, usermodel, fname): perplexity = int(len(words) ** 0.5) # We set perplexity to a square root of the words number embedding = TSNE(n_components=2, perplexity=perplexity, metric='cosine', n_iter=500, init='pca') y = embedding.fit_transform(matrix) print('2-d embedding finished', file=sys.stderr) class_set = [c for c in set(classes)] colors = plot.cm.rainbow(np.linspace(0, 1, len(class_set))) class2color = [colors[class_set.index(w)] for w in classes] xpositions = y[:, 0] ypositions = y[:, 1] seen = set() plot.clf() for color, word, class_label, x, y in zip(class2color, words, classes, xpositions, ypositions): plot.scatter(x, y, 20, marker='.', color=color, label=class_label if class_label not in seen else "") seen.add(class_label) lemma = word.split('_')[0].replace('::', ' ') mid = len(lemma) / 2 mid *= 4 # TODO Should really think about how to adapt this variable to the real plot size plot.annotate(lemma, xy=(x - mid, y), size='x-large', weight='bold', fontproperties=font, color=color) plot.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False) plot.tick_params(axis='y', which='both', left=False, right=False, labelleft=False) plot.legend(loc='best') plot.savefig(root + 'data/images/tsneplots/' + usermodel + '_' + fname + '.png', dpi=150, bbox_inches='tight') plot.close() plot.clf()
Example #19
Source File: experiment.py From double-dqn with MIT License | 5 votes |
def plot_training_episode_highscore(): pylab.clf() sns.set_context("poster") pylab.plot(0, 0) episodes = [0] highscore = [0] for n in xrange(len(csv_training_highscore)): params = csv_training_highscore[n] episodes.append(params[0]) highscore.append(params[1]) pylab.plot(episodes, highscore, sns.xkcd_rgb["windows blue"], lw=2) pylab.xlabel("episodes") pylab.ylabel("highscore") pylab.savefig("%s/training_episode_highscore.png" % args.plot_dir)
Example #20
Source File: TensorFlowInterface.py From IntroToDeepLearning with MIT License | 5 votes |
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None): # Output summary try: W = layer.output except: W = layer wp = W.eval(feed_dict=feed_dict); if len(np.shape(wp)) < 4: # Fully connected layer, has no shape temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel() fields = np.reshape(temp,[1]+fieldShape) else: # Convolutional layer already has shape wp = np.rollaxis(wp,3,0) features, channels, iy,ix = np.shape(wp) if channel is not None: fields = wp[:,channel,:,:] else: fields = np.reshape(wp,[features*channels,iy,ix]) perRow = int(math.floor(math.sqrt(fields.shape[0]))) perColumn = int(math.ceil(fields.shape[0]/float(perRow))) fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))]) tiled = [] for i in range(0,perColumn*perRow,perColumn): tiled.append(np.hstack(fields2[i:i+perColumn])) tiled = np.vstack(tiled) if figOffset is not None: mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar();
Example #21
Source File: TensorFlowInterface.py From IntroToDeepLearning with MIT License | 5 votes |
def plotFields(layer,fieldShape=None,channel=None,maxFields=25,figName='ReceptiveFields',cmap=None,padding=0.01): # Receptive Fields Summary W = layer.W wp = W.eval().transpose(); if len(np.shape(wp)) < 4: # Fully connected layer, has no shape fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape) else: # Convolutional layer already has shape features, channels, iy, ix = np.shape(wp) if channel is not None: fields = wp[:,channel,:,:] else: fields = np.reshape(wp,[features*channels,iy,ix]) fieldsN = min(fields.shape[0],maxFields) perRow = int(math.floor(math.sqrt(fieldsN))) perColumn = int(math.ceil(fieldsN/float(perRow))) fig = mpl.figure(figName); mpl.clf() # Using image grid from mpl_toolkits.axes_grid1 import ImageGrid grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single') for i in range(0,fieldsN): im = grid[i].imshow(fields[i],cmap=cmap); grid.cbar_axes[0].colorbar(im) mpl.title('%s Receptive Fields' % layer.name) # old way # fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))]) # tiled = [] # for i in range(0,perColumn*perRow,perColumn): # tiled.append(np.hstack(fields2[i:i+perColumn])) # # tiled = np.vstack(tiled) # mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar(); mpl.figure(figName+' Total'); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar()
Example #22
Source File: TensorFlowInterface.py From IntroToDeepLearning with MIT License | 5 votes |
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None): # Output summary W = layer.output wp = W.eval(feed_dict=feed_dict); if len(np.shape(wp)) < 4: # Fully connected layer, has no shape temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel() fields = np.reshape(temp,[1]+fieldShape) else: # Convolutional layer already has shape wp = np.rollaxis(wp,3,0) features, channels, iy,ix = np.shape(wp) if channel is not None: fields = wp[:,channel,:,:] else: fields = np.reshape(wp,[features*channels,iy,ix]) perRow = int(math.floor(math.sqrt(fields.shape[0]))) perColumn = int(math.ceil(fields.shape[0]/float(perRow))) fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))]) tiled = [] for i in range(0,perColumn*perRow,perColumn): tiled.append(np.hstack(fields2[i:i+perColumn])) tiled = np.vstack(tiled) if figOffset is not None: mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar();
Example #23
Source File: megafacade.py From facade-segmentation with MIT License | 5 votes |
def save_plots(self, folder): import pylab as pl pl.gcf().set_size_inches(15, 15) pl.clf() self.homography.plot_original() pl.savefig(join(folder, 'homography-original.jpg')) pl.clf() self.homography.plot_rectified() pl.savefig(join(folder, 'homography-rectified.jpg')) pl.clf() self.driving_layers.plot(overlay_alpha=0.7) pl.savefig(join(folder, 'segnet-driving.jpg')) pl.clf() self.facade_layers.plot(overlay_alpha=0.7) pl.savefig(join(folder, 'segnet-i12-facade.jpg')) pl.clf() self.plot_grids() pl.savefig(join(folder, 'grid.jpg')) pl.clf() self.plot_regions() pl.savefig(join(folder, 'regions.jpg')) pl.clf() pl.gcf().set_size_inches(6, 4) self.plot_facade_cuts() pl.savefig(join(folder, 'facade-cuts.jpg'), dpi=300) pl.savefig(join(folder, 'facade-cuts.svg')) imsave(join(folder, 'walls.png'), self.wall_colors)
Example #24
Source File: experiment.py From double-dqn with MIT License | 5 votes |
def plot_episode_reward(): pylab.clf() sns.set_context("poster") pylab.plot(0, 0) episodes = [0] scores = [0] for n in xrange(len(csv_episode)): params = csv_episode[n] episodes.append(params[0]) scores.append(params[1]) pylab.plot(episodes, scores, sns.xkcd_rgb["windows blue"], lw=2) pylab.xlabel("episodes") pylab.ylabel("score") pylab.savefig("%s/episode_reward.png" % args.plot_dir)
Example #25
Source File: generate_figs.py From discrete_sieve with Apache License 2.0 | 5 votes |
def save_digit(z, filename, cmap=pylab.cm.gray): pylab.clf() pylab.axis('off') pylab.imshow(z.reshape((28, 28)), interpolation='nearest', cmap=cmap, vmin=-1, vmax=1) pylab.savefig('results/' + filename + '.pdf') pylab.clf()
Example #26
Source File: spectrogram.py From spectrum with BSD 3-Clause "New" or "Revised" License | 5 votes |
def plot(self, filename=None, vmin=None, vmax=None, cmap='jet_r'): import pylab pylab.clf() pylab.imshow(-np.log10(self.results[self._start_y:,:]), origin="lower", aspect="auto", cmap=cmap, vmin=vmin, vmax=vmax) pylab.colorbar() # Fix xticks XMAX = float(self.results.shape[1]) # The max integer on xaxis xpos = list(range(0, int(XMAX), int(XMAX/5))) xx = [int(this*100)/100 for this in np.array(xpos) / XMAX * self.duration] pylab.xticks(xpos, xx, fontsize=16) # Fix yticks YMAX = float(self.results.shape[0]) # The max integer on xaxis ypos = list(range(0, int(YMAX), int(YMAX/5))) yy = [int(this) for this in np.array(ypos) / YMAX * self.sampling] pylab.yticks(ypos, yy, fontsize=16) #pylab.yticks([1000,2000,3000,4000], [5500,11000,16500,22000], fontsize=16) #pylab.title("%s echoes" % filename.replace(".png", ""), fontsize=25) pylab.xlabel("Time (seconds)", fontsize=25) pylab.ylabel("Frequence (Hz)", fontsize=25) pylab.tight_layout() if filename: pylab.savefig(filename)
Example #27
Source File: cwt_utils.py From Ossian with Apache License 2.0 | 5 votes |
def calc_prominence(params, labels, func=np.max, use_peaks = True): labelled = [] norm = params.astype(float) for (start, end, word) in labels: if end -start == 0: continue #print start, end, word if use_peaks: peaks = [] #pylab.clf() #pylab.plot(params[start:end]) (peaks, indices)=get_peaks(params[start:end]) if len(peaks) >0: labelled.append(np.max(peaks)) #labelled.append(norm[start-5+peaks[0]]) # labelled.append([word,func(params[start:end])]) else: labelled.append(0.0) else: #labelled.append([word, func(params[start-10:end])]) labelled.append(func(params[start:end])) #raw_input() return labelled
Example #28
Source File: horizontal_walking.py From pymanoid with GNU General Public License v3.0 | 5 votes |
def plot_mpc_preview(self): import pylab T = self.mpc_timestep h = stance.com.z g = -sim.gravity[2] trange = [sim.time + k * T for k in range(len(self.x_mpc.X))] pylab.ion() pylab.clf() pylab.subplot(211) pylab.plot(trange, [v[0] for v in self.x_mpc.X]) pylab.plot(trange, [v[0] - v[2] * h / g for v in self.x_mpc.X]) pylab.subplot(212) pylab.plot(trange, [v[0] for v in self.y_mpc.X]) pylab.plot(trange, [v[0] - v[2] * h / g for v in self.y_mpc.X])
Example #29
Source File: kwfile_dict.py From pysynphot with BSD 3-Clause "New" or "Revised" License | 5 votes |
def plot(self,label,outname): P.clf() P.plot(self.tra_Discrep,'.') P.ylabel('(pysyn-syn)/syn') P.title(label) P.savefig(outname)
Example #30
Source File: plots.py From ColorPy with GNU Lesser General Public License v2.1 | 4 votes |
def color_vs_param_plot ( param_list, rgb_colors, title, filename, tight = False, plotfunc = pylab.plot, xlabel = 'param', ylabel = 'RGB Color'): '''Plot for a color that varies with a parameter - In a two part figure, draw: top: color as it varies with parameter (x axis) low: r,g,b values, as linear 0.0-1.0 values, of the attempted color. param_list - list of parameters (x axis) rgb_colors - numpy array, one row for each param in param_list title - title for plot filename - filename to save plot to plotfunc - optional plot function to use (default pylab.plot) xlabel - label for x axis ylabel - label for y axis (default 'RGB Color') ''' pylab.clf () # draw color bars in upper plot pylab.subplot (2,1,1) pylab.title (title) # no xlabel, ylabel in upper plot num_points = len (param_list) for i in range (0, num_points-1): x0 = param_list [i] x1 = param_list [i+1] y0 = 0.0 y1 = 1.0 poly_x = [x0, x1, x1, x0] poly_y = [y0, y0, y1, y1] color_string = colormodels.irgb_string_from_rgb (rgb_colors [i]) pylab.fill (poly_x, poly_y, color_string, edgecolor=color_string) if tight: tighten_x_axis (param_list) # draw rgb curves in lower plot pylab.subplot (2,1,2) # no title in lower plot plotfunc (param_list, rgb_colors [:,0], color='r', label='Red') plotfunc (param_list, rgb_colors [:,1], color='g', label='Green') plotfunc (param_list, rgb_colors [:,2], color='b', label='Blue') if tight: tighten_x_axis (param_list) pylab.xlabel (xlabel) pylab.ylabel (ylabel) print ('Saving plot %s' % str (filename)) pylab.savefig (filename) # # Some specialized plots #