Python pylab.savefig() Examples

The following are 30 code examples of pylab.savefig(). 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: test_turbo_seti.py    From turbo_seti with MIT License 7 votes vote down vote up
def plot_hits(filename_fil, filename_dat):
    """ Plot the hits in a .dat file. """
    table = find_event.read_dat(filename_dat)
    print(table)

    plt.figure(figsize=(10, 8))
    N_hit = len(table)
    if N_hit > 10:
        print("Warning: More than 10 hits found. Only plotting first 10")
        N_hit = 10

    for ii in range(N_hit):
        plt.subplot(N_hit, 1, ii+1)
        plot_event.plot_hit(filename_fil, filename_dat, ii)
    plt.tight_layout()
    plt.savefig(filename_dat.replace('.dat', '.png'))
    plt.show() 
Example #2
Source File: func.py    From NEUCOGAR with GNU General Public License v2.0 6 votes vote down vote up
def save(GUI):
    global txtResultPath
    if GUI:
        import pylab as pl
        import nest.raster_plot
        import nest.voltage_trace
        logger.debug("Saving IMAGES into {0}".format(SAVE_PATH))
        for key in spikedetectors:
            try:
                nest.raster_plot.from_device(spikedetectors[key], hist=True)
                pl.savefig(f_name_gen(SAVE_PATH, "spikes_" + key.lower()), dpi=dpi_n, format='png')
                pl.close()
            except Exception:
                print(" * * * from {0} is NOTHING".format(key))
    txtResultPath = SAVE_PATH + 'txt/'
    logger.debug("Saving TEXT into {0}".format(txtResultPath))
    if not os.path.exists(txtResultPath):
        os.mkdir(txtResultPath)
    for key in spikedetectors:
        save_spikes(spikedetectors[key], name=key)
    with open(txtResultPath + 'timeSimulation.txt', 'w') as f:
        for item in times:
            f.write(item) 
Example #3
Source File: cartpole_a3c.py    From reinforcement-learning with MIT License 6 votes vote down vote up
def train(self):
        # self.load_model('./save_model/cartpole_a3c.h5')
        agents = [Agent(i, self.actor, self.critic, self.optimizer, self.env_name, self.discount_factor,
                        self.action_size, self.state_size) for i in range(self.threads)]

        for agent in agents:
            agent.start()

        while True:
            time.sleep(20)

            plot = scores[:]
            pylab.plot(range(len(plot)), plot, 'b')
            pylab.savefig("./save_graph/cartpole_a3c.png")

            self.save_model('./save_model/cartpole_a3c.h5') 
Example #4
Source File: analysis.py    From smallrnaseq with GNU General Public License v3.0 6 votes vote down vote up
def summarise_reads(path):
    """Count reads in all files in path"""

    resultfile = os.path.join(path, 'read_stats.csv')
    files = glob.glob(os.path.join(path,'*.fastq'))
    vals=[]
    rl=[]
    for f in files:
        label = os.path.splitext(os.path.basename(f))[0]
        s = utils.fastq_to_dataframe(f)
        l = len(s)
        vals.append([label,l])
        print (label, l)

    df = pd.DataFrame(vals,columns=['path','total reads'])
    df.to_csv(resultfile)
    df.plot(x='path',y='total reads',kind='barh')
    plt.tight_layout()
    plt.savefig(os.path.join(path,'total_reads.png'))
    #df = pd.concat()
    return df 
Example #5
Source File: plot_contrast_sensitive.py    From SceneChangeDet with MIT License 6 votes vote down vote up
def main():

    l2_base_dir = '/media/admin228/00027E210001A5BD/train_pytorch/change_detection/CMU/prediction_cons/l2_5,6,7/roc'
    cos_base_dir = '/media/admin228/00027E210001A5BD/train_pytorch/change_detection/CMU/prediction_cons/dist_cos_new_5,6,7/roc'
    CSF_dir = os.path.join(l2_base_dir)
    CSF_fig_dir = os.path.join(l2_base_dir,'fig.png')
    end_number = 22
    csf_conv5_l2_ls,csf_fc6_l2_ls,csf_fc7_l2_ls,x_l2 = get_csf_ls(l2_base_dir,end_number)
    csf_conv5_cos_ls,csf_fc6_cos_ls,csf_fc7_cos_ls,x_cos = get_csf_ls(cos_base_dir,end_number)
    Fig = pylab.figure()
    setFigLinesBW(Fig)
    #pylab.plot(x,csf_conv4_ls, color='k',label= 'conv4')
    pylab.plot(x_l2,csf_conv5_l2_ls, color='m',label= 'l2:conv5')
    pylab.plot(x_l2,csf_fc6_l2_ls, color = 'b',label= 'l2:fc6')
    pylab.plot(x_l2,csf_fc7_l2_ls, color = 'g',label= 'l2:fc7')
    pylab.plot(x_cos,csf_conv5_cos_ls, color='c',label= 'cos:conv5')
    pylab.plot(x_cos,csf_fc6_cos_ls, color = 'r',label= 'cos:fc6')
    pylab.plot(x_cos,csf_fc7_cos_ls, color = 'y',label= 'cos:fc7')
    pylab.legend(loc='lower right', prop={'size': 10})
    pylab.ylabel('RMS Contrast', fontsize=14)
    pylab.xlabel('Epoch', fontsize=14)
    pylab.savefig(CSF_fig_dir) 
Example #6
Source File: pncview.py    From pseudonetcdf with GNU Lesser General Public License v3.0 6 votes vote down vote up
def plot(ifile, varkey, options, before='', after=''):
    import pylab as pl
    outpath = getattr(options, 'outpath', '.')
    var = ifile.variables[varkey]
    dims = [(k, l) for l, k in zip(var[:].shape, var.dimensions) if l > 1]
    if len(dims) > 1:
        raise ValueError(
            'Plots can have only 1 non-unity dimensions; got %d - %s' %
            (len(dims), str(dims)))
    exec(before)
    ax = pl.gca()
    print(varkey, end='')
    if options.logscale:
        ax.set_yscale('log')

    ax.plot(var[:].squeeze())
    ax.set_xlabel('unknown')
    ax.set_ylabel(getattr(var, 'standard_name',
                          varkey).strip() + ' ' + var.units.strip())
    fmt = 'png'
    figpath = os.path.join(outpath + '_1d_' + varkey + '.' + fmt)
    exec(after)
    pl.savefig(figpath)
    print('Saved fig', figpath)
    return figpath 
Example #7
Source File: image_ocr.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
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() 
Example #8
Source File: image_ocr.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
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() 
Example #9
Source File: image_ocr.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
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() 
Example #10
Source File: image_ocr.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
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() 
Example #11
Source File: experiment.py    From double-dqn with MIT License 6 votes vote down vote up
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 #12
Source File: doscalars.py    From pysynphot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #13
Source File: empirical_line.py    From isofit with Apache License 2.0 6 votes vote down vote up
def _plot_example(xv, yv, b):
    """Plot for debugging purposes."""

    matplotlib.rcParams['font.family'] = "serif"
    matplotlib.rcParams['font.sans-serif'] = "Times"
    matplotlib.rcParams["legend.edgecolor"] = "None"
    matplotlib.rcParams["axes.spines.top"] = False
    matplotlib.rcParams["axes.spines.bottom"] = True
    matplotlib.rcParams["axes.spines.left"] = True
    matplotlib.rcParams["axes.spines.right"] = False
    matplotlib.rcParams['axes.grid'] = True
    matplotlib.rcParams['axes.grid.axis'] = 'both'
    matplotlib.rcParams['axes.grid.which'] = 'major'
    matplotlib.rcParams['legend.edgecolor'] = '1.0'
    plt.plot(xv[:, 113], yv[:, 113], 'ko')
    plt.plot(xv[:, 113], xv[:, 113] * b[113, 1] + b[113, 0], 'nneighbors')
    # plt.plot(x[113], x[113]*b[113, 1] + b[113, 0], 'ro')
    plt.grid(True)
    plt.xlabel('Radiance, $\mu{W }nm^{-1} sr^{-1} cm^{-2}$')
    plt.ylabel('Reflectance')
    plt.show(block=True)
    plt.savefig('empirical_line.pdf') 
Example #14
Source File: image_ocr.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
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() 
Example #15
Source File: image_ocr.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
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() 
Example #16
Source File: image_ocr.py    From pCVR with Apache License 2.0 6 votes vote down vote up
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() 
Example #17
Source File: image_ocr.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
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() 
Example #18
Source File: test.py    From CalculiX-Examples with MIT License 5 votes vote down vote up
def solid_plot():
	# reference values, see
	sref=0.0924102
	wref=0.000170152
	# List of the element types to process (text files)
	eltyps=["C3D8",
		"C3D8R",
		"C3D8I",
		"C3D20",
		"C3D20R",
		"C3D4",
		"C3D10"]
	pylab.figure(figsize=(10, 5.0), dpi=100)
	pylab.subplot(1,2,1)
	pylab.title("Stress")
	# pylab.hold(True) # deprecated
	for elty in eltyps:
		data = numpy.genfromtxt(elty+".txt")
		pylab.plot(data[:,1],data[:,2]/sref,"o-")
	pylab.xscale("log")
	pylab.xlabel('Number of nodes')
	pylab.ylabel('Max $\sigma / \sigma_{\mathrm{ref}}$')
	pylab.grid(True)
	pylab.subplot(1,2,2)
	pylab.title("Displacement")
	# pylab.hold(True) # deprecated
	for elty in eltyps:
		data = numpy.genfromtxt(elty+".txt")
		pylab.plot(data[:,1],data[:,3]/wref,"o-")
	pylab.xscale("log")
	pylab.xlabel('Number of nodes')
	pylab.ylabel('Max $u / u_{\mathrm{ref}}$')
	pylab.ylim([0,1.2])
	pylab.grid(True)
	pylab.legend(eltyps,loc="lower right")
	pylab.tight_layout()
	pylab.savefig("solid.svg",format="svg")
	# pylab.show()


# Move new files and folders to 'Refs' 
Example #19
Source File: pncview.py    From pseudonetcdf with GNU Lesser General Public License v3.0 5 votes vote down vote up
def timeseries(ifile, varkey, options, before='', after=''):
    import pylab as pl
    outpath = getattr(options, 'outpath', '.')
    time = gettime(ifile)
    var = ifile.variables[varkey]
    dims = [(k, l) for l, k in zip(var[:].shape, var.dimensions) if l > 1]
    if len(dims) > 1:
        raise ValueError(
            'Time series can have 1 non-unity dimensions; got %d - %s' %
            (len(dims), str(dims)))
    exec(before)
    ax = pl.gca()
    print(varkey, end='')
    if options.logscale:
        ax.set_yscale('log')

    ax.plot_date(time[:].squeeze(), var[:].squeeze())
    ax.set_xlabel(time.units.strip())
    ax.set_ylabel(getattr(var, 'standard_name',
                          varkey).strip() + ' ' + var.units.strip())
    fmt = 'png'
    figpath = os.path.join(outpath + '_ts_' + varkey + '.' + fmt)
    exec(after)
    pl.savefig(figpath)
    print('Saved fig', figpath)
    return figpath 
Example #20
Source File: helper.py    From KittiSeg with MIT License 5 votes vote down vote up
def saveBEVImageWithAxes(data, outputname, cmap = None, xlabel = 'x [m]', ylabel = 'z [m]', rangeX = [-10, 10], rangeXpx = None, numDeltaX = 5, rangeZ = [7, 62], rangeZpx = None, numDeltaZ = 5, fontSize = 16):
    '''
    
    :param data:
    :param outputname:
    :param cmap:
    '''
    aspect_ratio = float(data.shape[1])/data.shape[0]
    fig = pylab.figure()
    Scale = 8
    # add +1 to get axis text
    fig.set_size_inches(Scale*aspect_ratio+1,Scale*1)
    ax = pylab.gca()
    #ax.set_axis_off()
    #fig.add_axes(ax)
    if cmap != None:
        pylab.set_cmap(cmap)
    
    #ax.imshow(data, interpolation='nearest', aspect = 'normal')
    ax.imshow(data, interpolation='nearest')
    
    if rangeXpx == None:
        rangeXpx = (0, data.shape[1])
    
    if rangeZpx == None:
        rangeZpx = (0, data.shape[0])
        
    modBev_plot(ax, rangeX, rangeXpx, numDeltaX, rangeZ, rangeZpx, numDeltaZ, fontSize, xlabel = xlabel, ylabel = ylabel)
    #plt.savefig(outputname, bbox_inches='tight', dpi = dpi)
    pylab.savefig(outputname, dpi = data.shape[0]/Scale)
    pylab.close()
    fig.clear() 
Example #21
Source File: test_modcovar.py    From spectrum with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_figure():
    newpsd = test_modcovar()

    pylab.plot(pylab.linspace(-0.5, 0.5, 4096),
               10 * pylab.log10(newpsd/max(newpsd)))
    pylab.axis([-0.5,0.5,-60,0])
    pylab.savefig('psd_modcovar.png') 
Example #22
Source File: test_burg.py    From spectrum with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_figure():
    psd = test_burg()
    pylab.plot(pylab.linspace(-0.5, 0.5, len(psd)),
               10 * pylab.log10(psd/max(psd)))
    pylab.axis([-0.5,0.5,-60,0])
    pylab.savefig('psd_burg.png') 
Example #23
Source File: test_covar.py    From spectrum with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_figure():
    psd = test_pcovar()
    pylab.axis([-0.5,0.5,-60,0])
    pylab.savefig('psd_covar.png') 
Example #24
Source File: test_minvar.py    From spectrum with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_figure():
    res = test_minvar()
    psd = res[0]
    f = pylab.linspace(-0.5, 0.5, len(psd))
    pylab.plot(f, 10 * pylab.log10(psd/max(psd)), label='minvar 15')
    pylab.savefig('psd_minvar.png') 
Example #25
Source File: pncview.py    From pseudonetcdf with GNU Lesser General Public License v3.0 5 votes vote down vote up
def presslat(ifile, varkey, options, before='', after=''):
    import matplotlib.pyplot as plt
    from matplotlib.colors import Normalize, LogNorm
    outpath = getattr(options, 'outpath', '.')
    vert = cu.getpresbnds(ifile)
    lat, latunit = cu.getlatbnds(ifile)
    lat = np.append(lat.squeeze()[..., :2].mean(
        1), lat.squeeze()[-1, 2:].mean(0))
    var = ifile.variables[varkey]
    dims = [(k, l) for l, k in zip(var[:].shape, var.dimensions) if l > 1]
    if len(dims) > 2:
        raise ValueError(
            'Press-lat can have 2 non-unity dimensions; got %d - %s' %
            (len(dims), str(dims)))
    if options.logscale:
        norm = LogNorm()
    else:
        norm = Normalize()
    exec(before)
    ax = plt.gca()
    print(varkey, end='')
    patches = ax.pcolor(lat, vert, var[:].squeeze(), norm=norm)
    # ax.set_xlabel(X.units.strip())
    # ax.set_ylabel(Y.units.strip())
    cbar = plt.colorbar(patches)
    vunit = getattr(var, 'units', 'unknown').strip()
    cbar.set_label(varkey + ' (' + vunit + ')')
    cbar.ax.text(.5, 1, '%.2g' % var[:].max(
    ), horizontalalignment='center', verticalalignment='bottom')
    cbar.ax.text(.5, 0, '%.2g' % var[:].min(
    ), horizontalalignment='center', verticalalignment='top')
    ax.set_ylim(vert.max(), vert.min())
    ax.set_xlim(lat.min(), lat.max())
    fmt = 'png'
    figpath = os.path.join(outpath + '_PRESSLAT_' + varkey + '.' + fmt)
    exec(after)
    plt.savefig(figpath)
    print('Saved fig', figpath)
    return figpath 
Example #26
Source File: pncview.py    From pseudonetcdf with GNU Lesser General Public License v3.0 5 votes vote down vote up
def presslon(ifile, varkey, options, before='', after=''):
    import matplotlib.pyplot as plt
    from matplotlib.colors import Normalize, LogNorm
    outpath = getattr(options, 'outpath', '.')
    vert = cu.getpresbnds(ifile)
    lon, lonunit = cu.getlonbnds(ifile)
    lon = np.append(lon.squeeze()[..., [0, 3]].mean(
        1), lon.squeeze()[-1, [1, 2]].mean(0))
    var = ifile.variables[varkey]
    dims = [(k, l) for l, k in zip(var[:].shape, var.dimensions) if l > 1]
    if len(dims) > 2:
        raise ValueError(
            'Press-lon plots can have 2 non-unity dimensions; got %d - %s' %
            (len(dims), str(dims)))
    if options.logscale:
        norm = LogNorm()
    else:
        norm = Normalize()
    exec(before)
    ax = plt.gca()
    print(varkey, end='')
    patches = ax.pcolor(lon, vert, var[:].squeeze(), norm=norm)
    # ax.set_xlabel(X.units.strip())
    # ax.set_ylabel(Y.units.strip())
    cbar = plt.colorbar(patches)
    vunit = getattr(var, 'units', 'unknown').strip()
    cbar.set_label(varkey + ' (' + vunit + ')')
    cbar.ax.text(.5, 1, '%.2g' % var[:].max(
    ), horizontalalignment='center', verticalalignment='bottom')
    cbar.ax.text(.5, 0, '%.2g' % var[:].min(
    ), horizontalalignment='center', verticalalignment='top')

    ax.set_ylim(vert.max(), vert.min())
    ax.set_xlim(lon.min(), lon.max())
    fmt = 'png'
    figpath = os.path.join(outpath + '_PRESLON_' + varkey + '.' + fmt)
    exec(after)
    plt.savefig(figpath)
    print('Saved fig', figpath)
    return figpath 
Example #27
Source File: pncview.py    From pseudonetcdf with GNU Lesser General Public License v3.0 5 votes vote down vote up
def profile(ifile, varkey, options, before='', after=''):
    import matplotlib.pyplot as plt
    print(varkey, end='')
    outpath = getattr(options, 'outpath', '.')
    try:
        vert = cu.getpresmid(ifile)
        vunit = 'Pa'
    except Exception:
        vert = cu.getsigmamid(ifile)
        vunit = r'\sigma'
    var = ifile.variables[varkey]

    dims = list(var.dimensions)
    for knownvert in ['layer', 'LAY'] + ['layer%d' % i for i in range(72)]:
        if knownvert in dims:
            vidx = dims.index(knownvert)
            break
    else:
        raise KeyError("No known vertical coordinate; got %s" % str(dims))
    vert = vert[:var[:].shape[vidx]]
    units = var.units.strip()
    vals = np.rollaxis(var[:], vidx, start=0).view(
        np.ma.MaskedArray).reshape(vert.size, -1)
    ax = plt.gca()
    minmaxmean(ax, vals, vert)
    ax.set_xlabel(varkey + ' (' + units + ')')
    ax.set_ylabel(vunit)
    ax.set_ylim(vert.max(), vert.min())
    if options.logscale:
        ax.set_xscale('log')
    fmt = 'png'
    figpath = os.path.join(outpath + '_profile_' + varkey + '.' + fmt)
    exec(after)
    plt.savefig(figpath)
    print('Saved fig', figpath)
    return figpath 
Example #28
Source File: piecharts.py    From binaryanalysis with Apache License 2.0 5 votes vote down vote up
def generateImages(picklefile, pickledir, filehash, imagedir, pietype):

	leaf_file = open(os.path.join(pickledir, picklefile), 'rb')
	(piedata, pielabels) = cPickle.load(leaf_file)
	leaf_file.close()

	pylab.figure(1, figsize=(6.5,6.5))
	ax = pylab.axes([0.2, 0.15, 0.6, 0.6])

	pylab.pie(piedata, labels=pielabels)

	pylab.savefig(os.path.join(imagedir, '%s-%s.png' % (filehash, pietype)))
	pylab.gcf().clear()
	os.unlink(os.path.join(pickledir, picklefile)) 
Example #29
Source File: helper.py    From KittiSeg with MIT License 5 votes vote down vote up
def saveBEVImageWithAxes(data, outputname, cmap = None, xlabel = 'x [m]', ylabel = 'z [m]', rangeX = [-10, 10], rangeXpx = None, numDeltaX = 5, rangeZ = [7, 62], rangeZpx = None, numDeltaZ = 5, fontSize = 16):
    '''
    
    :param data:
    :param outputname:
    :param cmap:
    '''
    aspect_ratio = float(data.shape[1])/data.shape[0]
    fig = pylab.figure()
    Scale = 8
    # add +1 to get axis text
    fig.set_size_inches(Scale*aspect_ratio+1,Scale*1)
    ax = pylab.gca()
    #ax.set_axis_off()
    #fig.add_axes(ax)
    if cmap != None:
        pylab.set_cmap(cmap)
    
    #ax.imshow(data, interpolation='nearest', aspect = 'normal')
    ax.imshow(data, interpolation='nearest')
    
    if rangeXpx == None:
        rangeXpx = (0, data.shape[1])
    
    if rangeZpx == None:
        rangeZpx = (0, data.shape[0])
        
    modBev_plot(ax, rangeX, rangeXpx, numDeltaX, rangeZ, rangeZpx, numDeltaZ, fontSize, xlabel = xlabel, ylabel = ylabel)
    #plt.savefig(outputname, bbox_inches='tight', dpi = dpi)
    pylab.savefig(outputname, dpi = data.shape[0]/Scale)
    pylab.close()
    fig.clear() 
Example #30
Source File: pncview.py    From pseudonetcdf with GNU Lesser General Public License v3.0 5 votes vote down vote up
def pressx(ifile, varkey, options, before='', after=''):
    import matplotlib.pyplot as plt
    from matplotlib.colors import Normalize, LogNorm
    outpath = getattr(options, 'outpath', '.')
    vert = cu.getpresbnds(ifile)
    var = ifile.variables[varkey]
    dims = [(k, l) for l, k in zip(var[:].shape, var.dimensions) if l > 1]
    if len(dims) > 2:
        raise ValueError(
            'Press-x can have 2 non-unity dimensions; got %d - %s' %
            (len(dims), str(dims)))
    if options.logscale:
        norm = LogNorm()
    else:
        norm = Normalize()
    exec(before)
    ax = plt.gca()
    print(varkey, end='')
    vals = var[:].squeeze()
    x = np.arange(vals.shape[1])
    patches = ax.pcolor(x, vert, vals, norm=norm)
    # ax.set_xlabel(X.units.strip())
    # ax.set_ylabel(Y.units.strip())
    plt.colorbar(patches)
    ax.set_ylim(vert.max(), vert.min())
    ax.set_xlim(x.min(), x.max())
    fmt = 'png'
    figpath = os.path.join(outpath + '_PRESX_' + varkey + '.' + fmt)
    exec(after)
    plt.savefig(figpath)
    print('Saved fig', figpath)
    return figpath