Python pylab.tight_layout() Examples

The following are 22 code examples of pylab.tight_layout(). 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: analysis.py    From smallrnaseq with GNU General Public License v3.0 6 votes vote down vote up
def plot_pca(pX, palette='Spectral', labels=None, ax=None, colors=None):
    """Plot PCA result, input should be a dataframe"""

    if ax==None:
        fig,ax=plt.subplots(1,1,figsize=(6,6))
    cats = pX.index.unique()
    colors = sns.mpl_palette(palette, len(cats)+1)
    print (len(cats), len(colors))
    for c, i in zip(colors, cats):
        #print (i, len(pX.ix[i]))
        #if not i in pX.index: continue
        ax.scatter(pX.ix[i, 0], pX.ix[i, 1], color=c, s=90, label=i,
                   lw=.8, edgecolor='black', alpha=0.8)
    ax.set_xlabel('PC1')
    ax.set_ylabel('PC2')
    i=0
    if labels is not None:
        for n, point in pX.iterrows():
            l=labels[i]
            ax.text(point[0]+.1, point[1]+.1, str(l),fontsize=(9))
            i+=1
    ax.legend(fontsize=10,bbox_to_anchor=(1.5, 1.05))
    sns.despine()
    plt.tight_layout()
    return 
Example #3
Source File: plotting.py    From smallrnaseq with GNU General Public License v3.0 6 votes vote down vote up
def heatmap(df,fname=None,cmap='seismic',log=False):
    """Plot a heat map"""

    from matplotlib.colors import LogNorm
    f=plt.figure(figsize=(8,8))
    ax=f.add_subplot(111)
    norm=None
    df=df.replace(0,.1)
    if log==True:
        norm=LogNorm(vmin=df.min().min(), vmax=df.max().max())
    hm = ax.pcolor(df,cmap=cmap,norm=norm)
    plt.colorbar(hm,ax=ax,shrink=0.6,norm=norm)
    plt.yticks(np.arange(0.5, len(df.index), 1), df.index)
    plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns, rotation=90)
    #ax.axvline(4, color='gray'); ax.axvline(8, color='gray')
    plt.tight_layout()
    if fname != None:
        f.savefig(fname+'.png')
    return ax 
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: plotting.py    From smallrnaseq with GNU General Public License v3.0 6 votes vote down vote up
def plot_fractions(df, label=None):
    """Process results of multiple mappings to get fractions
    of each annotations mapped
    label: plot this sample only"""

    fig,ax = plt.subplots(figsize=(8,8))
    df = df.set_index('label')
    df = df._get_numeric_data()
    if len(df) == 1:
        label = df.index[0]
    if label != None:
        ax = df.T.plot(y=label,kind='pie',colormap='Spectral',autopct='%.1f%%',
                      startangle=0, labels=None,legend=True,pctdistance=1.1,
                      fontsize=10, ax=ax)
    else:
        ax = df.plot(kind='barh',stacked=True,linewidth=0,cmap='Spectral',ax=ax)
        #ax.legend(ncol=2)
        ax.set_position([0.2,0.1,0.6,0.8])
        ax.legend(loc="best",bbox_to_anchor=(1.0, .9))
    plt.title('fractions mapped')
    #plt.tight_layout()
    return fig 
Example #6
Source File: plotting.py    From smallrnaseq with GNU General Public License v3.0 6 votes vote down vote up
def plot_read_count_dists(counts, h=8, n=50):
    """Boxplots of read count distributions """

    scols,ncols = base.get_column_names(counts)
    df = counts.sort_values(by='mean_norm',ascending=False)[:n]
    df = df.set_index('name')[ncols]
    t = df.T
    w = int(h*(len(df)/60.0))+4
    fig, ax = plt.subplots(figsize=(w,h))
    if len(scols) > 1:
        sns.stripplot(data=t,linewidth=1.0,palette='coolwarm_r')
        ax.xaxis.grid(True)
    else:
        df.plot(kind='bar',ax=ax)
    sns.despine(offset=10,trim=True)
    ax.set_yscale('log')
    plt.setp(ax.xaxis.get_majorticklabels(), rotation=90)
    plt.ylabel('read count')
    #print (df.index)
    #plt.tight_layout()
    fig.subplots_adjust(bottom=0.2,top=0.9)
    return fig 
Example #7
Source File: iris_recognition.py    From GmdhPy with MIT License 5 votes vote down vote up
def plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues):
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(iris.target_names))
    plt.xticks(tick_marks, iris.target_names, rotation=45)
    plt.yticks(tick_marks, iris.target_names)
    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label') 
Example #8
Source File: __init__.py    From EDeN with MIT License 5 votes vote down vote up
def plot_confusion_matrices(y_true, y_pred, size=12):
    """plot_confusion_matrices."""
    plt.figure(figsize=(size, size))
    plt.subplot(121)
    plot_confusion_matrix(y_true, y_pred, normalize=False)
    plt.subplot(122)
    plot_confusion_matrix(y_true, y_pred, normalize=True)
    plt.tight_layout(w_pad=5)
    plt.show() 
Example #9
Source File: prcNetwork.py    From Motiftoolbox with GNU General Public License v2.0 5 votes vote down vote up
def show(self):
		from pylab import figure, subplot, plot, show, tight_layout

		phase = np.arange(0., 2.*np.pi+0.01, 0.01)

		fig = figure()
		ax = fig.add_subplot(1, 1, 1)
		tight_layout()
		show() 
Example #10
Source File: prcNetwork.py    From Motiftoolbox with GNU General Public License v2.0 5 votes vote down vote up
def plot(self, GRID=10, ax=None, **kwargs):

		NEWAXIS = False
		if ax == None:
			from pylab import figure, show
			fig = figure()
			ax = fig.add_subplot(111)
			NEWAXIS = True

		if "period" in kwargs:
			period = kwargs.pop("period")
		else:
			period = tl.PI2


		phase = tl.PI2*np.arange(GRID)/float(GRID-1)
		phase += phase[1]/2.
		UV = np.asarray([ [self([phase[i], phase[j]]) for i in xrange(GRID)]	# Spalten
								for j in xrange(GRID)])	# Zeilen

		X, Y = np.meshgrid(phase, phase)
		U, V = UV[:, :, 0], UV[:, :, 1]
	
		Q = ax.quiver(period*X/tl.PI2, period*Y/tl.PI2, U, V, units='width')

		for fp in self.fixedPoints:
			fp.plot(axis=ax, period=period)
			
		if NEWAXIS:
			ax.set_xlim(0., period)
			ax.set_ylim(0., period)
			fig.tight_layout()
			show()

		return Q 
Example #11
Source File: spectrogram.py    From spectrum with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 #12
Source File: srnabench.py    From smallrnaseq with GNU General Public License v3.0 5 votes vote down vote up
def analyse_results(k,n,outpath=None):
    """Summarise multiple results"""

    if outpath != None:
        os.chdir(outpath)
    #add mirbase info
    k = k.merge(mirbase,left_on='name',right_on='mature1')
    ky1 = 'unique reads'
    ky2 = 'read count' #'RC'
    cols = ['name','freq','mean read count','mean_norm','total','perc','mirbase_id']
    print
    print ('found:')
    idcols,normcols = get_column_names(k)
    final = filter_expr_results(k,freq=.8,meanreads=200)
    print (final[cols])
    print ('-------------------------------')
    print ('%s total' %len(k))
    print ('%s with >=10 mean reads' %len(k[k['mean read count']>=10]))
    print ('%s found in 1 sample only' %len(k[k['freq']==1]))
    print ('top 10 account for %2.2f' %k['perc'][:10].sum())

    fig,ax = plt.subplots(nrows=1, ncols=1, figsize=(8,6))
    k.set_index('name')['total'][:10].plot(kind='barh',colormap='Spectral',ax=ax,log=True)
    plt.tight_layout()
    fig.savefig('srnabench_top_known.png')
    #fig = plot_read_count_dists(final)
    #fig.savefig('srnabench_known_counts.png')
    fig,ax = plt.subplots(figsize=(10,6))
    k[idcols].sum().plot(kind='bar',ax=ax)
    fig.savefig('srnabench_total_persample.png')
    print
    k.to_csv('srnabench_known_all.csv',index=False)
    return k 
Example #13
Source File: plotting.py    From smallrnaseq with GNU General Public License v3.0 5 votes vote down vote up
def plot_sample_counts(counts):

    fig,ax = plt.subplots(figsize=(10,6))
    scols,ncols = base.get_column_names(counts)
    counts[scols].sum().plot(kind='bar',ax=ax)
    plt.title('total counts per sample (unnormalised)')
    plt.tight_layout()
    return fig 
Example #14
Source File: plotting.py    From smallrnaseq with GNU General Public License v3.0 5 votes vote down vote up
def plot_sample_variation(df):

    fig,axs=plt.subplots(2,1,figsize=(6,6))
    axs=axs.flat
    cols,ncols = mirdeep2.get_column_names(m)
    x = m.ix[2][cols]
    x.plot(kind='bar',ax=axs[0])
    x2 = m.ix[2][ncols]
    x2.plot(kind='bar',ax=axs[1])
    sns.despine(trim=True,offset=10)
    plt.tight_layout()
    return fig 
Example #15
Source File: analyser.py    From spotpy with MIT License 5 votes vote down vote up
def plot_objectivefunctiontraces(results,evaluation,algorithms,fig_name='Like_trace.png'):
    import matplotlib.pyplot as plt
    from matplotlib import colors
    cnames=list(colors.cnames)
    font = {'family' : 'calibri',
        'weight' : 'normal',
        'size'   : 20}
    plt.rc('font', **font)
    fig=plt.figure(figsize=(16,3))
    xticks=[5000,15000]

    for i in range(len(results)):
        ax  = plt.subplot(1,len(results),i+1)
        likes=calc_like(results[i],evaluation,spotpy.objectivefunctions.rmse)
        ax.plot(likes,'b-')
        ax.set_ylim(0,25)
        ax.set_xlim(0,len(results[0]))
        ax.set_xlabel(algorithms[i])
        ax.xaxis.set_ticks(xticks)
        if i==0:
            ax.set_ylabel('RMSE')
            ax.yaxis.set_ticks([0,10,20])
        else:
            ax.yaxis.set_ticks([])

    plt.tight_layout()
    fig.savefig(fig_name) 
Example #16
Source File: analyser.py    From spotpy with MIT License 5 votes vote down vote up
def plot_parametertrace_algorithms(result_lists, algorithmnames, spot_setup, 
                                   fig_name='parametertrace_algorithms.png'):
    """Example Plot as seen in the SPOTPY Documentation"""
    import matplotlib.pyplot as plt
    font = {'family' : 'calibri',
        'weight' : 'normal',
        'size'   : 20}
    plt.rc('font', **font)
    fig=plt.figure(figsize=(17,5))
    subplots=len(result_lists)
    parameter = spotpy.parameter.get_parameters_array(spot_setup)
    rows=len(parameter['name'])
    for j in range(rows):
        for i in range(subplots):
            ax  = plt.subplot(rows,subplots,i+1+j*subplots)
            data=result_lists[i]['par'+parameter['name'][j]]
            ax.plot(data,'b-')
            if i==0:
                ax.set_ylabel(parameter['name'][j])
                rep = len(data)
            if i>0:
                ax.yaxis.set_ticks([])
            if j==rows-1:
                ax.set_xlabel(algorithmnames[i-subplots])
            else:
                ax.xaxis.set_ticks([])
            ax.plot([1]*rep,'r--')
            ax.set_xlim(0,rep)
            ax.set_ylim(parameter['minbound'][j],parameter['maxbound'][j])
            
    #plt.tight_layout()
    fig.savefig(fig_name, bbox_inches='tight') 
Example #17
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 #18
Source File: mesh_viewer.py    From MeshCNN with MIT License 5 votes vote down vote up
def plot_mesh(mesh, *whats, show=True, plot=None):
    for what in [update_plot] + list(whats):
        plot = what(mesh, plot)
    if show:
        li = max(plot[1][1], plot[1][3], plot[1][5])
        plot[0].auto_scale_xyz([0, li], [0, li], [0, li])
        pl.tight_layout()
        pl.show()
    return plot 
Example #19
Source File: __init__.py    From EDeN with MIT License 5 votes vote down vote up
def plot_aucs(y_true, y_score, size=12):
    """plot_confusion_matrices."""
    plt.figure(figsize=(size, size / 2.0))
    plt.subplot(121, aspect='equal')
    plot_roc_curve(y_true, y_score)
    plt.subplot(122, aspect='equal')
    plot_precision_recall_curve(y_true, y_score)
    plt.tight_layout(w_pad=5)
    plt.show() 
Example #20
Source File: srnabench.py    From smallrnaseq with GNU General Public License v3.0 4 votes vote down vote up
def analyse_isomirs(iso,outpath=None):
    """Analyse isomiR results in detail"""

    if iso is None:
        return
    if outpath != None:
        os.chdir(outpath)
    subcols = ['name','read','isoClass','NucVar','total','freq']
    iso = iso.sort_values('total', ascending=False)
    #filter very low abundance reads
    iso = iso[(iso.total>10) & (iso.freq>0.5)]
    top = get_top_isomirs(iso)
    top.to_csv('srnabench_isomirs_dominant.csv',index=False)
    print ('top isomiRs:')
    print (top[:20])
    print ('%s/%s with only 1 isomir' %(len(top[top.domisoperc==1]),len(top)))
    print ('different dominant isomir:', len(top[top.variant!='exact'])/float(len(top)))
    print ('mean dom isomir perc:', top.domisoperc.mean())
    print
    #stats
    fig,ax = plt.subplots(1,1)
    top.plot('isomirs','total',kind='scatter',logy=True,logx=True,alpha=0.8,s=50,ax=ax)
    ax.set_title('no. isomiRs per miRNA vs total adundance')
    ax.set_xlabel('no. isomiRs')
    ax.set_ylabel('total reads')
    fig.savefig('srnabench_isomir_counts.png')
    fig,ax = plt.subplots(1,1)
    #top.hist('domisoperc',bins=20,ax=ax)
    try:
        base.sns.distplot(top.domisoperc,bins=15,ax=ax,kde_kws={"lw": 2})
    except:
        pass
    fig.suptitle('distribution of dominant isomiR share of reads')
    fig.savefig('srnabench_isomir_domperc.png')

    x = iso[iso.name.isin(iso.name[:28])]
    bins=range(15,30,1)
    ax = x.hist('length',bins=bins,ax=ax,by='name',sharex=True,alpha=0.9)
    ax[-1,-1].set_xlabel('length')
    fig.suptitle('isomiR length distributions')
    fig.savefig('srnabench_isomir_lengths.png')
    plt.close('all')

    c=iso.variant.value_counts()
    #c=c[c>10]
    fig,ax = plt.subplots(1,1,figsize=(8,8))
    c.plot(kind='pie',colormap='Spectral',ax=ax, labels=None,legend=True,
             startangle=0,pctdistance=1.1,autopct='%.1f%%',fontsize=10)
    ax.set_title('isomiR class distribution')
    plt.tight_layout()
    fig.savefig('srnabench_isomir_classes.png')

    iso.to_csv('srnabench_isomirs_all.csv',index=False)
    return top 
Example #21
Source File: vis_corex.py    From LinearCorex with GNU Affero General Public License v3.0 4 votes vote down vote up
def plot_rels(data, labels=None, colors=None, outfile="rels", latent=None, alpha=0.8, title=''):
    ns, n = data.shape
    if labels is None:
        labels = list(map(str, list(range(n))))
    ncol = 5
    nrow = int(np.ceil(float(n * (n - 1) / 2) / ncol))

    fig, axs = pylab.subplots(nrow, ncol)
    fig.set_size_inches(5 * ncol, 5 * nrow)
    pairs = list(combinations(list(range(n)), 2))
    if colors is not None:
        colors = (colors - np.min(colors)) / (np.max(colors) - np.min(colors))

    for ax, pair in zip(axs.flat, pairs):
        diff_x = max(data[:, pair[0]]) - min(data[:, pair[0]])
        diff_y = max(data[:, pair[1]]) - min(data[:, pair[1]])
        ax.set_xlim([min(data[:, pair[0]]) - 0.05 * diff_x, max(data[:, pair[0]]) + 0.05 * diff_x])
        ax.set_ylim([min(data[:, pair[1]]) - 0.05 * diff_y, max(data[:, pair[1]]) + 0.05 * diff_y])
        ax.scatter(data[:, pair[0]], data[:, pair[1]], c=colors, cmap=pylab.get_cmap("jet"),
                       marker='.', alpha=alpha, edgecolors='none', vmin=0, vmax=1)

        ax.set_xlabel(shorten(labels[pair[0]]))
        ax.set_ylabel(shorten(labels[pair[1]]))

    for ax in axs.flat[axs.size - 1:len(pairs) - 1:-1]:
        ax.scatter(data[:, 0], data[:, 1], marker='.')

    fig.suptitle(title, fontsize=16)
    pylab.rcParams['font.size'] = 12  #6
    # pylab.draw()
    # fig.set_tight_layout(True)
    pylab.tight_layout()
    pylab.subplots_adjust(top=0.95)
    for ax in axs.flat[axs.size - 1:len(pairs) - 1:-1]:
        ax.set_visible(False)
    filename = outfile + '.png'
    if not os.path.exists(os.path.dirname(filename)):
        os.makedirs(os.path.dirname(filename))
    fig.savefig(outfile + '.png')
    pylab.close('all')
    return True


# Hierarchical graph visualization utilities 
Example #22
Source File: multiple_files.py    From orbkit with GNU Lesser General Public License v3.0 4 votes vote down vote up
def plot(self,mo_matrix,symmetry='1',title='All',x_label='index',
           y_label='MO coefficients',output_format='png',
           plt_dir='Plots',ylim=None,thresh=0.1,x0=0,grid=True,x_grid=None,**kwargs):
    '''Plots all molecular orbital coefficients of one self.symmetry.'''
    import pylab as plt
    from matplotlib.ticker import MultipleLocator
    import os
    
    display('Plotting data of self.symmetry %s to %s/' % (symmetry,plt_dir))
    if not os.path.exists(plt_dir):
      os.makedirs(plt_dir)
    
    if numpy.ndim(mo_matrix) == 2:
      mo_matrix = mo_matrix[:,numpy.newaxis,:]
    
    shape = numpy.shape(mo_matrix)
    
    
    def plot_mo(i):
      fig=plt.figure()
      plt.rc('xtick', labelsize=16) 
      plt.rc('ytick', labelsize=16)
      ax = plt.subplot(111)
      curves=[]
      for ij in range(shape[2]):
        Y = mo_matrix[:,i,ij]
        if x_grid is None:
          X = numpy.arange(len(Y))+x0
        else:
          X = x_grid
        if max(numpy.abs(Y)) > thresh:
          curves.append(ax.plot(X,Y, '.-' ,linewidth=1.5))
      
      
      plt.xlabel(x_label, fontsize=16);
      plt.ylabel(y_label, fontsize=16);
      plt.title('%s: %d.%s'%  (title,i+1,symmetry))
      plt.ylim(ylim)
      
      plt.tight_layout()
      return fig
    
    if output_format == 'pdf':
      from matplotlib.backends.backend_pdf import PdfPages
      output_fid = '%s.%s.pdf'% (title,symmetry.replace(' ','_'))
      display('\t%s' % output_fid)
      with PdfPages(os.path.join(plt_dir,output_fid)) as pdf:
        for i in range(shape[1]):
          fig = plot_mo(i)
          pdf.savefig(fig,**kwargs)
          plt.close()
    elif output_format == 'png':
      for i in range(shape[1]):
        fig = plot_mo(i)
        output_fid = '%d.%s.png' % (i+1,symmetry.replace(' ','_'))
        display('\t%s' % output_fid)
        fig.savefig(os.path.join(plt_dir, output_fid),format='png',**kwargs)
        plt.close()
    else:
      raise ValueError('output_format `%s` is not supported' % output_format)