Python matplotlib.pylab.savefig() Examples

The following are 30 code examples of matplotlib.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 matplotlib.pylab , or try the search function .
Example #1
Source File: plot_errors_boxplot.py    From MDI with MIT License 7 votes vote down vote up
def plot(params_dir):
    model_dirs = [name for name in os.listdir(params_dir)
                  if os.path.isdir(os.path.join(params_dir, name))]

    df = defaultdict(list)
    for model_dir in model_dirs:
        df[re.sub('_bin_scaled_mono_True_ratio', '', model_dir)] = [
            dd.io.load(path)['best_epoch']['validate_objective']
            for path in glob.glob(os.path.join(
                params_dir, model_dir) + '/*.h5')]

    df = pd.DataFrame(dict([(k, pd.Series(v)) for k, v in df.iteritems()]))
    df.to_csv(os.path.basename(os.path.normpath(params_dir)))
    plt.figure(figsize=(16, 4), dpi=300)
    g = sns.boxplot(df)
    g.set_xticklabels(df.columns, rotation=45)
    plt.tight_layout()
    plt.savefig('{}_errors_box_plot.png'.format(
        os.path.join(IMAGES_DIRECTORY,
                     os.path.basename(os.path.normpath(params_dir))))) 
Example #2
Source File: benchmark.py    From osqp_benchmarks with Apache License 2.0 6 votes vote down vote up
def plot_performance_profiles(problems, solvers):
    """
    Plot performance profiles in matplotlib for specified problems and solvers
    """
    # Remove OSQP polish solver
    solvers = solvers.copy()
    for s in solvers:
        if "polish" in s:
            solvers.remove(s)

    df = pd.read_csv('./results/%s/performance_profiles.csv' % problems)
    plt.figure(0)
    for solver in solvers:
        plt.plot(df["tau"], df[solver], label=solver)
    plt.xlim(1., 10000.)
    plt.ylim(0., 1.)
    plt.xlabel(r'Performance ratio $\tau$')
    plt.ylabel('Ratio of problems solved')
    plt.xscale('log')
    plt.legend()
    plt.grid()
    plt.show(block=False)
    results_file = './results/%s/%s.png' % (problems, problems)
    print("Saving plots to %s" % results_file)
    plt.savefig(results_file) 
Example #3
Source File: run_lookup.py    From rasa_lookup_demo with Apache License 2.0 6 votes vote down vote up
def plot_metrics(metric_list, save_path=None):
    # runs through each test case and adds a set of bars to a plot.  Saves

    f, (ax1) = plt.subplots(1, 1)
    plt.grid(True)

    print_metrics(metric_list)

    bar_metrics(metric_list[0], ax1, index=0)
    bar_metrics(metric_list[1], ax1, index=1)
    bar_metrics(metric_list[2], ax1, index=2)

    if save_path is None:
        save_path = "img/bar_" + key + ".png"

    plt.savefig(save_path, dpi=400) 
Example #4
Source File: testfuncs.py    From Computable with MIT License 6 votes vote down vote up
def plotallfuncs(allfuncs=allfuncs):
    from matplotlib import pylab as pl
    pl.ioff()
    nnt = NNTester(npoints=1000)
    lpt = LinearTester(npoints=1000)
    for func in allfuncs:
        print(func.title)
        nnt.plot(func, interp=False, plotter='imshow')
        pl.savefig('%s-ref-img.png' % func.func_name)
        nnt.plot(func, interp=True, plotter='imshow')
        pl.savefig('%s-nn-img.png' % func.func_name)
        lpt.plot(func, interp=True, plotter='imshow')
        pl.savefig('%s-lin-img.png' % func.func_name)
        nnt.plot(func, interp=False, plotter='contour')
        pl.savefig('%s-ref-con.png' % func.func_name)
        nnt.plot(func, interp=True, plotter='contour')
        pl.savefig('%s-nn-con.png' % func.func_name)
        lpt.plot(func, interp=True, plotter='contour')
        pl.savefig('%s-lin-con.png' % func.func_name)
    pl.ion() 
Example #5
Source File: utils.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 6 votes vote down vote up
def plot_feat_importance(feature_names, clf, name):
    pylab.clf()
    coef_ = clf.coef_
    important = np.argsort(np.absolute(coef_.ravel()))
    f_imp = feature_names[important]
    coef = coef_.ravel()[important]
    inds = np.argsort(coef)
    f_imp = f_imp[inds]
    coef = coef[inds]
    xpos = np.array(range(len(coef)))
    pylab.bar(xpos, coef, width=1)

    pylab.title('Feature importance for %s' % (name))
    ax = pylab.gca()
    ax.set_xticks(np.arange(len(coef)))
    labels = ax.set_xticklabels(f_imp)
    for label in labels:
        label.set_rotation(90)
    filename = name.replace(" ", "_")
    pylab.savefig(os.path.join(
        CHART_DIR, "feat_imp_%s.png" % filename), bbox_inches="tight") 
Example #6
Source File: prod_basis.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def generate_png_chess_dp_vertex(self):
    """Produces pictures of the dominant product vertex a chessboard convention"""
    import matplotlib.pylab as plt
    plt.ioff()
    dab2v = self.get_dp_vertex_doubly_sparse()
    for i, ab in enumerate(dab2v): 
        fname = "chess-v-{:06d}.png".format(i)
        print('Matrix No.#{}, Size: {}, Type: {}'.format(i+1, ab.shape, type(ab)), fname)
        if type(ab) != 'numpy.ndarray': ab = ab.toarray()
        fig = plt.figure()
        ax = fig.add_subplot(1,1,1)
        ax.set_aspect('equal')
        plt.imshow(ab, interpolation='nearest', cmap=plt.cm.ocean)
        plt.colorbar()
        plt.savefig(fname)
        plt.close(fig) 
Example #7
Source File: demo_mi.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 6 votes vote down vote up
def plot_entropy():
    pylab.clf()
    pylab.figure(num=None, figsize=(5, 4))

    title = "Entropy $H(X)$"
    pylab.title(title)
    pylab.xlabel("$P(X=$coin will show heads up$)$")
    pylab.ylabel("$H(X)$")

    pylab.xlim(xmin=0, xmax=1.1)
    x = np.arange(0.001, 1, 0.001)
    y = -x * np.log2(x) - (1 - x) * np.log2(1 - x)
    pylab.plot(x, y)
    # pylab.xticks([w*7*24 for w in [0,1,2,3,4]], ['week %i'%(w+1) for w in
    # [0,1,2,3,4]])

    pylab.autoscale(tight=True)
    pylab.grid(True)

    filename = "entropy_demo.png"
    pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight") 
Example #8
Source File: utils.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 6 votes vote down vote up
def plot_confusion_matrix(cm, genre_list, name, title):
    pylab.clf()
    pylab.matshow(cm, fignum=False, cmap='Blues', vmin=0, vmax=1.0)
    ax = pylab.axes()
    ax.set_xticks(range(len(genre_list)))
    ax.set_xticklabels(genre_list)
    ax.xaxis.set_ticks_position("bottom")
    ax.set_yticks(range(len(genre_list)))
    ax.set_yticklabels(genre_list)
    pylab.title(title)
    pylab.colorbar()
    pylab.grid(False)
    pylab.show()
    pylab.xlabel('Predicted class')
    pylab.ylabel('True class')
    pylab.grid(False)
    pylab.savefig(
        os.path.join(CHART_DIR, "confusion_matrix_%s.png" % name), bbox_inches="tight") 
Example #9
Source File: utils.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 6 votes vote down vote up
def plot_roc(auc_score, name, tpr, fpr, label=None):
    pylab.clf()
    pylab.figure(num=None, figsize=(5, 4))
    pylab.grid(True)
    pylab.plot([0, 1], [0, 1], 'k--')
    pylab.plot(fpr, tpr)
    pylab.fill_between(fpr, tpr, alpha=0.5)
    pylab.xlim([0.0, 1.0])
    pylab.ylim([0.0, 1.0])
    pylab.xlabel('False Positive Rate')
    pylab.ylabel('True Positive Rate')
    pylab.title('ROC curve (AUC = %0.2f) / %s' %
                (auc_score, label), verticalalignment="bottom")
    pylab.legend(loc="lower right")
    filename = name.replace(" ", "_")
    pylab.savefig(
        os.path.join(CHART_DIR, "roc_" + filename + ".png"), bbox_inches="tight") 
Example #10
Source File: utils.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 6 votes vote down vote up
def plot_feat_importance(feature_names, clf, name):
    pylab.figure(num=None, figsize=(6, 5))
    coef_ = clf.coef_
    important = np.argsort(np.absolute(coef_.ravel()))
    f_imp = feature_names[important]
    coef = coef_.ravel()[important]
    inds = np.argsort(coef)
    f_imp = f_imp[inds]
    coef = coef[inds]
    xpos = np.array(list(range(len(coef))))
    pylab.bar(xpos, coef, width=1)

    pylab.title('Feature importance for %s' % (name))
    ax = pylab.gca()
    ax.set_xticks(np.arange(len(coef)))
    labels = ax.set_xticklabels(f_imp)
    for label in labels:
        label.set_rotation(90)
    filename = name.replace(" ", "_")
    pylab.savefig(os.path.join(
        CHART_DIR, "feat_imp_%s.png" % filename), bbox_inches="tight") 
Example #11
Source File: testfuncs.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def plotallfuncs(allfuncs=allfuncs):
    from matplotlib import pylab as pl
    pl.ioff()
    nnt = NNTester(npoints=1000)
    lpt = LinearTester(npoints=1000)
    for func in allfuncs:
        print(func.title)
        nnt.plot(func, interp=False, plotter='imshow')
        pl.savefig('%s-ref-img.png' % func.func_name)
        nnt.plot(func, interp=True, plotter='imshow')
        pl.savefig('%s-nn-img.png' % func.func_name)
        lpt.plot(func, interp=True, plotter='imshow')
        pl.savefig('%s-lin-img.png' % func.func_name)
        nnt.plot(func, interp=False, plotter='contour')
        pl.savefig('%s-ref-con.png' % func.func_name)
        nnt.plot(func, interp=True, plotter='contour')
        pl.savefig('%s-nn-con.png' % func.func_name)
        lpt.plot(func, interp=True, plotter='contour')
        pl.savefig('%s-lin-con.png' % func.func_name)
    pl.ion() 
Example #12
Source File: variable_describe.py    From convis with GNU General Public License v3.0 6 votes vote down vote up
def _plot_to_string():
    try:
        from StringIO import StringIO
        make_bytes = lambda x: x.buf
    except ImportError:
        from io import BytesIO as StringIO
        make_bytes = lambda x: x.getbuffer()
    try:
        from urllib import quote
    except:
        from urllib.parse import quote
    import base64
    import matplotlib.pylab as plt
    imgdata = StringIO()
    plt.savefig(imgdata)
    plt.close()
    imgdata.seek(0) 
    image = base64.encodestring(make_bytes(imgdata))
    return str(quote(image)) 
Example #13
Source File: kNN.py    From statistical-learning-methods-note with Apache License 2.0 6 votes vote down vote up
def plotKChart(self, misClassDict, saveFigPath):
        kList = []
        misRateList = []
        for k, misClassNum in misClassDict.iteritems():
            kList.append(k)
            misRateList.append(1.0 - 1.0/k*misClassNum)

        fig = plt.figure(saveFigPath)
        plt.plot(kList, misRateList, 'r--')
        plt.title(saveFigPath)
        plt.xlabel('k Num.')
        plt.ylabel('Misclassified Rate')
        plt.legend(saveFigPath)
        plt.grid(True)
        plt.savefig(saveFigPath)
        plt.show()

################################### PART3 TEST ########################################
# 例子 
Example #14
Source File: data_augmentation.py    From ConvNetQuake with MIT License 6 votes vote down vote up
def plot_true_and_augmented_data(sample,noised_sample,label,n_examples):
    output_dir = os.path.split(FLAGS.output)[0]
    # Save augmented data
    plt.clf()
    fig, ax = plt.subplots(3,1)
    for t in range(noised_sample.shape[1]):
        ax[t].plot(noised_sample[:,t])
        ax[t].set_xlabel('time (samples)')
        ax[t].set_ylabel('amplitude')
    ax[0].set_title('window {:03d}, cluster_id: {}'.format(n_examples,label))
    plt.savefig(os.path.join(output_dir, "augmented_data",
                            'augmented_{:03d}.pdf'.format(n_examples)))
    plt.close()

    # Save true data
    plt.clf()
    fig, ax = plt.subplots(3,1)
    for t in range(sample.shape[1]):
        ax[t].plot(sample[:,t])
        ax[t].set_xlabel('time (samples)')
        ax[t].set_ylabel('amplitude')
    ax[0].set_title('window {:03d}, cluster_id: {}'.format(n_examples,label))
    plt.savefig(os.path.join(output_dir, "true_data",
                            'true__{:03d}.pdf'.format(n_examples)))
    plt.close() 
Example #15
Source File: testfuncs.py    From ImageFusion with MIT License 6 votes vote down vote up
def plotallfuncs(allfuncs=allfuncs):
    from matplotlib import pylab as pl
    pl.ioff()
    nnt = NNTester(npoints=1000)
    lpt = LinearTester(npoints=1000)
    for func in allfuncs:
        print(func.title)
        nnt.plot(func, interp=False, plotter='imshow')
        pl.savefig('%s-ref-img.png' % func.__name__)
        nnt.plot(func, interp=True, plotter='imshow')
        pl.savefig('%s-nn-img.png' % func.__name__)
        lpt.plot(func, interp=True, plotter='imshow')
        pl.savefig('%s-lin-img.png' % func.__name__)
        nnt.plot(func, interp=False, plotter='contour')
        pl.savefig('%s-ref-con.png' % func.__name__)
        nnt.plot(func, interp=True, plotter='contour')
        pl.savefig('%s-nn-con.png' % func.__name__)
        lpt.plot(func, interp=True, plotter='contour')
        pl.savefig('%s-lin-con.png' % func.__name__)
    pl.ion() 
Example #16
Source File: reportStats.py    From gemBS with GNU General Public License v3.0 6 votes vote down vote up
def drawMapqHistogram(self):
        """ From matplot lib plots a Mappping qualty histogram
        """
        #1. PLOT BUILDING
        readsMapq = self.mapping_stats.mapping_quality_reads
       
        mapqList = list(range(len(readsMapq)))
     
        matplotlib.pyplot.ioff()
        figure = plt.figure()
        plt.bar(mapqList,readsMapq,width=1,align='center',facecolor='blue', alpha=0.75)
        plt.xlabel('MapQ')
        plt.ylabel('Fragments')
        plt.title('MapQ Histogram')
        plt.axis([0, 60,min(readsMapq), max(readsMapq)])
        plt.grid(True)
        
        pylab.savefig(self.png_mapq_histogram)
        
        plt.close(figure) 
Example #17
Source File: PlotComps.py    From refinery with MIT License 6 votes vote down vote up
def main():
  args = parse_args()
  jobpath, taskids = parse_jobpath_and_taskids(args)

  for taskid in taskids:
    taskpath = os.path.join(jobpath, taskid)
    if args.lap is not None:
      prefix, bLap = ModelReader.getPrefixForLapQuery(taskpath, args.lap)      
      if bLap != args.lap:
        print 'Using saved lap: ', bLap
    else:
      prefix = 'Best' # default

    hmodel = ModelReader.load_model(taskpath, prefix)
    plotModelInNewFigure(jobpath, hmodel, args)
    if args.savefilename is not None:
      pylab.show(block=False)
      pylab.savefig(args.savefilename % (taskid))
  
  if args.savefilename is None:
    pylab.show(block=True) 
Example #18
Source File: graph-bot.py    From discord-bots with MIT License 6 votes vote down vote up
def matrix(msg, mobj):
    """
    Interpret a user string, convert it to a list and graph it as a matrix
    Uses ast.literal_eval to parse input into a list
    """
    fname = bot_data("{}.png".format(mobj.author.id))
    try:
        list_input = literal_eval(msg)
        if not isinstance(list_input, list):
            raise ValueError("Not a list")
        m = np_matrix(list_input)
        fig = plt.figure()
        ax = fig.add_subplot(1,1,1)
        ax.set_aspect('equal')
        plt.imshow(m, interpolation='nearest', cmap=plt.cm.ocean)
        plt.colorbar()
        plt.savefig(fname)
        await client.send_file(mobj.channel, fname)
        f_remove(fname)
        return
    except Exception as ex:
        logger("!matrix: {}".format(ex))
    return await client.send_message(mobj.channel, "Failed to render graph") 
Example #19
Source File: testfuncs.py    From neural-network-animation with MIT License 6 votes vote down vote up
def plotallfuncs(allfuncs=allfuncs):
    from matplotlib import pylab as pl
    pl.ioff()
    nnt = NNTester(npoints=1000)
    lpt = LinearTester(npoints=1000)
    for func in allfuncs:
        print(func.title)
        nnt.plot(func, interp=False, plotter='imshow')
        pl.savefig('%s-ref-img.png' % func.__name__)
        nnt.plot(func, interp=True, plotter='imshow')
        pl.savefig('%s-nn-img.png' % func.__name__)
        lpt.plot(func, interp=True, plotter='imshow')
        pl.savefig('%s-lin-img.png' % func.__name__)
        nnt.plot(func, interp=False, plotter='contour')
        pl.savefig('%s-ref-con.png' % func.__name__)
        nnt.plot(func, interp=True, plotter='contour')
        pl.savefig('%s-nn-con.png' % func.__name__)
        lpt.plot(func, interp=True, plotter='contour')
        pl.savefig('%s-lin-con.png' % func.__name__)
    pl.ion() 
Example #20
Source File: evaluate.py    From text-classifier with Apache License 2.0 6 votes vote down vote up
def plot_pr(auc_score, precision, recall, label=None, figure_path=None):
    """绘制R/P曲线"""
    try:
        from matplotlib import pylab
        pylab.figure(num=None, figsize=(6, 5))
        pylab.xlim([0.0, 1.0])
        pylab.ylim([0.0, 1.0])
        pylab.xlabel('Recall')
        pylab.ylabel('Precision')
        pylab.title('P/R (AUC=%0.2f) / %s' % (auc_score, label))
        pylab.fill_between(recall, precision, alpha=0.5)
        pylab.grid(True, linestyle='-', color='0.75')
        pylab.plot(recall, precision, lw=1)
        pylab.savefig(figure_path)
    except Exception as e:
        print("save image error with matplotlib")
        pass 
Example #21
Source File: plotting_utils.py    From nonparaSeq2seqVC_code with MIT License 5 votes vote down vote up
def plot_alignment(alignment, fn):
    # [4, encoder_step, decoder_step] 
    fig, axes = plt.subplots(1, 2)

    for j in range(2):
        g = axes[j].imshow(alignment[j,:,:].T,
            aspect='auto', origin='lower',
            interpolation='none')
        plt.colorbar(g, ax=axes[j])
    
    plt.savefig(fn)
    plt.close()
    return fn 
Example #22
Source File: inference.py    From nonparaSeq2seqVC_code with MIT License 5 votes vote down vote up
def plot_data(data, fn, figsize=(12, 4)):
    fig, axes = plt.subplots(1, len(data), figsize=figsize)
    for i in range(len(data)):
        if len(data) == 1:
            ax = axes
        else:
            ax = axes[i]
        g = ax.imshow(data[i], aspect='auto', origin='bottom', 
                       interpolation='none')
        plt.colorbar(g, ax=ax)
    plt.savefig(fn) 
Example #23
Source File: inference_utils.py    From nonparaSeq2seqVC_code with MIT License 5 votes vote down vote up
def plot_data(data, fn, figsize=(12, 4)):
    fig, axes = plt.subplots(1, len(data), figsize=figsize)
    for i in range(len(data)):
        if len(data) == 1:
            ax = axes
        else:
            ax = axes[i]
        g = ax.imshow(data[i], aspect='auto', origin='bottom', 
                       interpolation='none')
        plt.colorbar(g, ax=ax)
    plt.savefig(fn) 
Example #24
Source File: lr_finder.py    From signaltrain with GNU General Public License v3.0 5 votes vote down vote up
def lrfind(model, dataloader, optimizer, calc_loss, start=1e-6, stop=4e-3, num_lrs=150, to_screen=False):
    """ Learning Rate finder.  See leslie howard, sylvian gugger & jeremy howard's work """
    print("Running LR Find:",end="",flush=True)

    lrs, losses = [], []
    lr_tries = np.logspace(np.log10(start), np.log10(stop), num_lrs)
    ind, count, repeat = 0, 0, 3
    for x, y, knobs in dataloader:
        count+=1
        if ind >= len(lr_tries):
            break
        lr_try = lr_tries[ind]
        if count % repeat ==0:  # repeat over this many data points per lr value
            ind+=1
            print(".",sep="",end="",flush=True)
        optimizer.param_groups[0]['lr'] = lr_try

        #x_cuda, y_cuda, knobs_cuda = datagen.new()
        x_cuda, y_cuda, knobs_cuda = x.to(device), y.to(device), knobs.to(device)
        x_hat, mag, mag_hat = model.forward(x_cuda, knobs_cuda)
        loss = calc_loss(x_hat.float() ,y_cuda.float(), mag.float())
        lrs.append(lr_try)
        losses.append(loss.item())
        optimizer.zero_grad()
        loss.backward()
        model.clip_grad_norm_()
        optimizer.step()

    plt.figure(1)
    plt.semilogx(lrs,losses)
    if to_screen:
        plt.show()
    else:
        outfile = 'lrfind.png'
        plt.savefig(outfile)
        plt.close(plt.gcf())
        print("\nLR Find finished. See "+outfile)
    return 
Example #25
Source File: io_methods.py    From signaltrain with GNU General Public License v3.0 5 votes vote down vote up
def plot_valdata(x_val_cuda, knobs_val_cuda, y_val_cuda, y_val_hat_cuda, effect, \
	epoch, loss_val, file_prefix='val_data', num_plots=50, target_size=None):

	x_size = len(x_val_cuda.data.cpu().numpy()[0])
	if target_size is None:
		y_size = len(y_val_cuda.data.cpu().numpy()[0])
	else:
		y_size = target_size
	t_small = range(x_size-y_size, x_size)
	for plot_i in range(0, num_plots):
		x_val = x_val_cuda.data.cpu().numpy()
		knobs_w = effect.knobs_wc( knobs_val_cuda.data.cpu().numpy()[plot_i,:] )
		plt.figure(plot_i,figsize=(6,8))
		titlestr = f'{effect.name} Val data, epoch {epoch+1}, loss_val = {loss_val.item():.3e}\n'
		for i in range(len(effect.knob_names)):
		    titlestr += f'{effect.knob_names[i]} = {knobs_w[i]:.2f}'
		    if i < len(effect.knob_names)-1: titlestr += ', '
		plt.suptitle(titlestr)
		plt.subplot(3, 1, 1)
		plt.plot(x_val[plot_i, :], 'b', label='Input')
		plt.ylim(-1,1)
		plt.xlim(0,x_size)
		plt.legend()
		plt.subplot(3, 1, 2)
		y_val = y_val_cuda.data.cpu().numpy()
		plt.plot(t_small, y_val[plot_i, -y_size:], 'r', label='Target')
		plt.xlim(0,x_size)
		plt.ylim(-1,1)
		plt.legend()
		plt.subplot(3, 1, 3)
		plt.plot(t_small, y_val[plot_i, -y_size:], 'r', label='Target')
		y_val_hat = y_val_hat_cuda.data.cpu().numpy()
		plt.plot(t_small, y_val_hat[plot_i, -y_size:], c=(0,0.5,0,0.85), label='Predicted')
		plt.ylim(-1,1)
		plt.xlim(0,x_size)
		plt.legend()
		filename = file_prefix + '_' + str(plot_i) + '.png'
		savefig(filename)
	return 
Example #26
Source File: reportStats.py    From gemBS with GNU General Public License v3.0 5 votes vote down vote up
def drawInsertSizePlot(self):
        """ From matplot lib plots a Insert Size Plot
        """
        iSizeList = []
        readsList = []
        
        #1. PLOT BUILDING
        histogram_template_len = self.mapping_stats.read_insert_size_histogram
        
        for insert_size_length,reads in histogram_template_len.items():
            iSizeList.append(int(insert_size_length))
            readsList.append(int(reads))
            
        matplotlib.pyplot.ioff()            
        figure = plt.figure()

        plt.plot(iSizeList, readsList, '.',color="r")
        plt.xlabel('Insert Size (bp)')
        plt.ylabel('Reads')
        plt.title('Insert Size Histogram')
        plt.axis([min(iSizeList), 800,min(readsList), max(readsList)])
        plt.grid(True)
        
        pylab.savefig(self.png_insert_size_histogram)
        
        plt.close(figure) 
Example #27
Source File: reportStats.py    From gemBS with GNU General Public License v3.0 5 votes vote down vote up
def drawMultipleInsertSizePlot(self):
        """ From matplot lib plots a Insert Size Plot
        """ 
        iSizeList = []
        readsList = []
        readsYaxis = []
        sizeXaxis = []
        lanesNames = []
        
        #1. PLOT BUILDING
        for laneStats in self.mapping_stats.list_lane_stats:
            lanesNames.append(laneStats.name)
            histogram_template_len = laneStats.read_insert_size_histogram
            sizeList  = []
            readList = []
            for insert_size_length,reads in histogram_template_len.items():
                sizeList.append(int(insert_size_length))
                readList.append(int(reads))
                
            readsYaxis.extend(readList)
            sizeXaxis.extend(sizeList)
            iSizeList.append(sizeList)
            readsList.append(readList)
            
        matplotlib.pyplot.ioff()            
        figure = plt.figure()

        for iSize, readList in zip(iSizeList, readsList):        
            plt.plot(iSize, readList,'.')
        
        plt.xlabel('Insert Size (bp)')
        plt.ylabel('Reads')
        plt.title('Insert Size Histogram Per Lane')
        plt.axis([min(sizeXaxis), 800,min(readsYaxis), max(readsYaxis)])
        plt.legend(lanesNames,loc='upper right')        
        
        plt.grid(True)
       
        pylab.savefig(self.png_insert_size_histogram)
        
        plt.close(figure) 
Example #28
Source File: plotting_utils.py    From nonparaSeq2seqVC_code with MIT License 5 votes vote down vote up
def plot_alignment(alignment, fn):
    # [4, encoder_step, decoder_step] 
    fig, axes = plt.subplots(2, 2)
    for i in range(2):
        for j in range(2):
            g = axes[i][j].imshow(alignment[i*2+j,:,:].T,
                aspect='auto', origin='lower',
                interpolation='none')
            plt.colorbar(g, ax=axes[i][j])
    
    plt.savefig(fn)
    plt.close()
    return fn 
Example #29
Source File: reportStats.py    From gemBS with GNU General Public License v3.0 5 votes vote down vote up
def drawMultipleMapqHistogram(self):
        """ From matplot lib plots a Mappping qualty histogram
        """  
        mapqFragmentsLanes = []
              
        for laneStats in self.mapping_stats.list_lane_stats:
            mapqFragmentsLanes.append(laneStats.mapping_quality_reads)
    
        matplotlib.pyplot.ioff()
        figure = plt.figure()
        ax = figure.add_subplot(111,projection='3d')
                       
        lane = 0
        for fragmentsQuality in mapqFragmentsLanes:
            qualityRange = list(range(len(fragmentsQuality)))            
            ax.bar(qualityRange,fragmentsQuality, zs=lane, zdir='y', color='b', alpha=0.8)
            lane = lane + 1
            
        ax.set_xlabel('MapQ')
        ax.set_ylabel('Lanes')
        ax.set_zlabel('Fragments')        
                
        #http://people.duke.edu/~ccc14/pcfb/numpympl/MatplotlibBarPlots.html
        pylab.savefig(self.png_mapq_histogram)
        
        plt.close(figure) 
Example #30
Source File: bsCallStats.py    From gemBS with GNU General Public License v3.0 5 votes vote down vote up
def saveAndClose(self):
        """Save the figure and close it"""
        pylab.savefig(self.pngFile)
        plt.close(self.figure)