当前位置: 首页>>代码示例>>Python>>正文


Python PdfPages.savefig方法代码示例

本文整理汇总了Python中matplotlib.backends.backend_pdf.PdfPages.savefig方法的典型用法代码示例。如果您正苦于以下问题:Python PdfPages.savefig方法的具体用法?Python PdfPages.savefig怎么用?Python PdfPages.savefig使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.backends.backend_pdf.PdfPages的用法示例。


在下文中一共展示了PdfPages.savefig方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: output

# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import savefig [as 别名]
def output(f, directory, folder, filename, extra=None, pdf=False, show=None):
    """Output the file in the defined folder """
    pd = os.path.normpath(os.path.join(dir,directory,folder))
    try:
        os.stat(os.path.dirname(pd))
    except:
        os.mkdir(os.path.dirname(pd))
    try:
        os.stat(pd)
    except:
        os.mkdir(pd)    
    
    # Saving 
    if not extra:
        f.savefig(os.path.join(pd,filename), facecolor='w', edgecolor='w', bbox_inches='tight', dpi=300)
    else:
        f.savefig(os.path.join(pd,filename), facecolor='w', edgecolor='w', bbox_extra_artists=(extra), bbox_inches='tight',dpi=300)
    
    if pdf:
        try:
            pp = PdfPages(os.path.join(pd,filename) + '.pdf')
            pp.savefig(f, bbox_extra_artists=(extra),bbox_inches='tight') 
            pp.close()
        except:
            print("ERROR: Problem in PDF conversion. Skipped.")
    if show:
        plt.show()
开发者ID:jovesus,项目名称:reg-gen,代码行数:29,代码来源:Main.py

示例2: plot_psi_weights

# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import savefig [as 别名]
def plot_psi_weights(output,
                     modelfile='/d/monk/eigenbrot/WIYN/14B-0456/anal/models/allZ2_vardisp/allz2_vardisp_batch_interp.fits'):
    #Like the last page of all the fit plots, but for all pointings at once
    #cribbed from plot_bc_vardisp.py

    m = pyfits.open(modelfile)[1].data[0]
    numZ = np.unique(m['Z'][:,0]).size
    numAge = np.unique(m['AGE'][:,0]).size
    big_W = np.zeros((numZ,numAge))
    
    for p in range(6):
        coeffile = 'NGC_891_P{}_bin30_allz2.coef.fits'.format(p+1)
        print coeffile
        coef_arr = pyfits.open(coeffile)[1].data
        numap = coef_arr['VSYS'].size
        
        for i in range(numap):
            wdata = coef_arr[i]['LIGHT_FRAC'].reshape(numZ,numAge)
            big_W += wdata/np.max(wdata)

    bwax = plt.figure().add_subplot(111)
    bwax.imshow(big_W,origin='lower',cmap='Blues',interpolation='none')
    bwax.set_xlabel('SSP Age [Gyr]')
    bwax.set_xticks(range(numAge))
    bwax.set_xticklabels(m['AGE'][:numAge,0]/1e9)
    bwax.set_ylabel(r'$Z/Z_{\odot}$')
    bwax.set_yticks(range(numZ))
    bwax.set_yticklabels(m['Z'][::numAge,0])

    pp = PDF(output)
    pp.savefig(bwax.figure)
    pp.close()
    plt.close(bwax.figure)
    
    return
开发者ID:eigenbrot,项目名称:snakes,代码行数:37,代码来源:NGC_paper_plots.py

示例3: profile_batch

# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import savefig [as 别名]
def profile_batch(radius,output):

    pp = PDF(output)

    for sim in glob('sim*.fits'):
        print sim

        header = pyfits.open(sim)[0].header
        w = header['W']
        N = header['N']
        pitch = header['PITCH']
        ang = header['VIEWANG']
        pitch = int(np.pi*2/pitch)
        ang = int(np.pi*2/ang)
        v, line, _ = salty.line_profile(sim,radius,pxbin=4.,plot=False)
        ax = plt.figure().add_subplot(111)
        ax.set_xlabel('Velocity [km/s]')
        ax.set_ylabel('Normalized power')
        ax.set_title(sim)
        ax.text(300,0.005,
                '$w={}$\n$N={}$\n$p=\\tau/{}$\n$\\theta_{{view}}=\\tau/{}$'.\
                    format(w,N,pitch,ang))
        ax.plot(v,line)
        pp.savefig(ax.figure)
    
    pp.close()
开发者ID:eigenbrot,项目名称:snakes,代码行数:28,代码来源:spiral_signal.py

示例4: plot_data_comb_2D

# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import savefig [as 别名]
    def plot_data_comb_2D(self, results_path, file_n, data, fit, timepoints):

        pp = PdfPages(results_path+'/'+file_n)
        cc = 0
        for tp in timepoints:
            xmin, xmax = -3, 3
            ymin, ymax = -3, 3

            xx, yy = mgrid[xmin:xmax:100j, ymin:ymax:100j]
            positions = vstack([xx.ravel(), yy.ravel()])
            values = vstack([ log10(1+data[tp][:, 0]), log10(1+data[tp][:, 1])])
            kernel = st.gaussian_kde(values)
            f = reshape(kernel(positions).T, xx.shape)

            xxf, yyf = mgrid[xmin:xmax:100j, ymin:ymax:100j]
            positions_f = vstack([xxf.ravel(), yyf.ravel()])
            values_f = vstack([log10(1+fit[tp][:, 0]), log10(1+fit[tp][:, 1])])
            kernel_f = st.gaussian_kde(values_f)
            ff = reshape(kernel_f(positions_f).T, xxf.shape)

            ax = plt.subplot(4, 5, cc+1)
            ax.contourf(xx, yy, f, cmap='Blues')
            ax.contourf(xxf, yyf, ff, cmap='Reds')

            ax.set_xlim([-1, 3])
            ax.set_ylim([-1, 3])
            cc += 1
        pp.savefig()
        plt.close()
        pp.close()
开发者ID:ucl-cssb,项目名称:ABC-Flow,代码行数:32,代码来源:flowOutput.py

示例5: print_pdf_graph

# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import savefig [as 别名]
def print_pdf_graph(file_f, regulon, conn):
  pdf = PdfPages(file_f)
  edgesLimits = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]
  #CRP = regulon_set['LexA']
  for lim in edgesLimits:
    print lim
    g = buildSimilarityGraph_top_10_v2(conn, lim)

    # Here the node is motif, eg 87878787_1, the first 8 digits represent gi
    node_color = [ 1 if node[0:8] in regulon else 0 for node in g ]

    pos = nx.graphviz_layout(g, prog="neato")
    plt.figure(figsize=(10.0, 10.0))
    plt.axis("off")
    nx.draw(g,
        pos,
        node_color = node_color,
        node_size = 20,
        alpha=0.8,
        with_labels=False,
        cmap=plt.cm.jet,
        vmax=1.0,
        vmin=0.0
        )
    pdf.savefig()
    plt.close()

  pdf.close()
开发者ID:Chuan-Zh,项目名称:footprint,代码行数:30,代码来源:regulon_cluster_by_top_edges.py

示例6: err_histogram

# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import savefig [as 别名]
def err_histogram(output, basedir='.',bins=10, field='MLWA', err='dMLWA', suffix='coef',
                  label=r'$\delta\tau_{L,\mathrm{fit}}/\tau_L$',exclude=exclude, ymax=90):

    ratio_list = []

    for p in range(6):
        coef = '{}/NGC_891_P{}_bin30_allz2.{}.fits'.format(basedir,p+1,suffix)
        print coef
        c = pyfits.open(coef)[1].data
        tmp = c[err]
        if field == 'TAUV':
            tmp *= 1.086
        else:
            tmp /= c[field]            
        tmp = np.delete(tmp,np.array(exclude[p]) - 1)
        ratio_list.append(tmp)

    ratio = np.hstack(ratio_list)
    ratio = ratio[ratio == ratio]
    ratio = ratio[np.where(ratio < 0.8)[0]]
    ax = plt.figure().add_subplot(111)
    ax.set_xlabel(label)
    ax.set_ylabel(r'$N$')
    ax.hist(ratio, bins=bins, histtype='step', color='k')
    ax.set_xlim(0,0.52)
    ax.set_xticks([0,0.1,0.2,0.3,0.4,0.5])
    ax.set_ylim(0,ymax)
    ax.set_yticks(range(0,int(ymax/10)*10+10,int(int(ymax/10)/4)*10))

    pp = PDF(output)
    pp.savefig(ax.figure)
    pp.close()
    plt.close(ax.figure)

    return
开发者ID:eigenbrot,项目名称:snakes,代码行数:37,代码来源:plot_allZ2.py

示例7: make_comp_plot_1D

# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import savefig [as 别名]
    def make_comp_plot_1D(self, results_path, file_n, data, sims, timepoints, ind=0):

        pp = PdfPages(results_path+'/'+file_n)
        cc = 0
        xmin, xmax = -1, 7
        x_grid = linspace(xmin, xmax, 1000)

        def kernel_est(d, ind, x_grid):
            dl = log10(1+d[:, ind])
            #dl[isneginf(dl)] = 0
            dl = dl[isfinite(dl)]
            kde = st.gaussian_kde(dl, bw_method=0.2)
            pdf = kde.evaluate(x_grid)
            return pdf

        for tp in timepoints:

            pdf_data = kernel_est(data[tp], ind, x_grid)
            pdf_sim = kernel_est(sims[tp], ind, x_grid)
            ax = plt.subplot(4, 5, cc + 1)
            ax.plot(x_grid, pdf_data, color='blue', alpha=0.5, lw=3)
            ax.plot(x_grid, pdf_sim, color='red', alpha=0.5, lw=3)
            cc += 1

        pp.savefig()
        plt.close()
        pp.close()
开发者ID:ucl-cssb,项目名称:ABC-Flow,代码行数:29,代码来源:flowOutput.py

示例8: show_or_save

# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import savefig [as 别名]
def show_or_save(plt, fig, use_x11, filename):
	if use_x11:
		plt.show()
	else:
		pp = PdfPages(filename)
		pp.savefig(fig)
		pp.close()
开发者ID:JWUST,项目名称:benchmark,代码行数:9,代码来源:plt_parallel_users.py

示例9: heat_map_single

# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import savefig [as 别名]
def heat_map_single(data, file = "heat_map_plate.pdf", *args, **kwargs):
    """ Create a heat_map for a single readout

    Create a heat_map for a single readout

    ..todo:: Share code between heat_map_single and heat_map_multiple
    """

    np_data = data.data
    pp = PdfPages(os.path.join(PATH, file))

    fig, ax = plt.subplots()

    im = ax.pcolormesh(np_data, vmin=np_data.min(), vmax=np_data.max()) # cmap='RdBu'
    fig.colorbar(im)

    # put the major ticks at the middle of each cell
    ax.set_xticks(np.arange(np_data.shape[1]) + 0.5, minor=False)
    ax.set_yticks(np.arange(np_data.shape[0]) + 0.5, minor=False)

    # Invert the y-axis such that the data is displayed as it appears on the plate.
    ax.invert_yaxis()
    ax.xaxis.tick_top()

    ax.set_xticklabels(data.axes['x'], minor=False)
    ax.set_yticklabels(data.axes['y'], minor=False)

    pp.savefig(fig)
    pp.close()
    fig.clear()

    return ax
开发者ID:elkeschaper,项目名称:hts,代码行数:34,代码来源:qc_matplotlib.py

示例10: plotDifElev

# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import savefig [as 别名]
def plotDifElev(outputname, outDir, title, x, y, colour, xlabel, ylabel, plttitle):
    """Plot modelled data.
	To use: plotDifElev(outputname,outDir, title, x, y, colour)"""
    #
    matplotlib.rcParams["axes.grid"] = True
    matplotlib.rcParams["legend.fancybox"] = True
    matplotlib.rcParams["figure.figsize"] = 11.69, 8.27  # A4
    matplotlib.rcParams["savefig.dpi"] = 300
    plotName = outputname + ".pdf"
    pp1 = PdfPages(os.path.join(outDir, plotName))
    fig1 = plt.figure(1)
    ax1 = fig1.add_subplot(111)
    xmax = max(x)
    xmin = min(x)
    labelString = title
    ax1.plot(x, y, color=colour, marker="o", linestyle="None", label=labelString)
    matplotlib.pyplot.axes().set_position([0.04, 0.065, 0.8, 0.9])
    ax1.plot([xmin / 1.01, xmax * 1.01], [0, 0], "-k")
    plt.axis([xmin / 1.01, xmax * 1.01, -2, 2])
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.title(plttitle)
    pp1.savefig(bbox_inches="tight")
    pp1.close()
    plt.close()
    return 0
开发者ID:mercergeoinfo,项目名称:LSA,代码行数:28,代码来源:LSASO.py

示例11: plotDif

# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import savefig [as 别名]
def plotDif(outputname, outDir, title, x, y, colour):
    """Plot modelled data.
	To use: plotDif(outputname,outDir, title, x, y, colour)"""
    #
    matplotlib.rcParams["axes.grid"] = True
    matplotlib.rcParams["legend.fancybox"] = True
    matplotlib.rcParams["figure.figsize"] = 11.69, 8.27  # A4
    matplotlib.rcParams["savefig.dpi"] = 300
    plotName = outputname + ".pdf"
    pp1 = PdfPages(os.path.join(outDir, plotName))
    fig1 = plt.figure(1)
    ax1 = fig1.add_subplot(111)
    xmax = max(x)
    xmin = min(x)
    ymax = max(y)
    ymin = min(y)
    labelString = title
    ax1.plot(x, y, color=colour, marker="o", linestyle="None", label=labelString)
    matplotlib.pyplot.axes().set_position([0.04, 0.065, 0.8, 0.9])
    ax1.legend(bbox_to_anchor=(0.0, 1), loc=2, borderaxespad=0.1, ncol=3, title="Julian Day")
    ax1.plot([xmin, xmax], [xmin, xmax], "-k")
    plt.axis([xmin + 0.1, xmax + 0.1, ymin + 0.1, ymax + 0.1])
    plt.xlabel("Measured Melt (m.w.e.)")
    plt.ylabel("Modelled Melt (m.w.e.)")
    plt.title("Modelled against Measured")
    # plt.show()
    pp1.savefig(bbox_inches="tight")
    pp1.close()
    plt.close()
    return 0
开发者ID:mercergeoinfo,项目名称:LSA,代码行数:32,代码来源:LSASO.py

示例12: srv_anomaly_qoe_liftchart

# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import savefig [as 别名]
def srv_anomaly_qoe_liftchart(datafolder, observe_srv, method, anormaly_name):
	plt_styles = ['k-', 'b-.', 'r:', 'm--', 'y-s', 'k-+', 'g-^', 'b-o', 'r-*', 'm-d']
	cmp_srv_qoes = {}
	cmp_srv_load = {}

	filter_obj = dict(filter_key="Server", filter_value=observe_srv)
	filesuffix = '_' + method + '.json'
	srv_qoes = filter_read_by_suffix(datafolder + '/' + anormaly_name + '/', filesuffix, filter_obj)
	cmp_srv_qoes[anormaly_name] = srv_qoes

	srv_qoes = filter_read_by_suffix(datafolder + '/normal/', filesuffix, filter_obj)
	cmp_srv_qoes['normal'] = srv_qoes

	fig, ax = plt.subplots()
	plt_count = 0

	for key in cmp_srv_qoes:
		print "Processing ", len(cmp_srv_qoes[key]), " streaming sessions in ", key, "!"
		cmp_srv_load[key] = len(cmp_srv_qoes[key])
		draw_lift_chart(cmp_srv_qoes[key], plt_styles[plt_count], key)
		plt_count = plt_count + 1

	ax.set_xlabel(r'User Percentile', fontsize=20)
	ax.set_ylabel(r'Session QoE', fontsize=20)
	ax.set_title('Compare users\' QoE lift curve with server ' + observe_srv + " with and without " + anormaly_name + " using method " + method, fontsize=20)
	plt.legend(bbox_to_anchor=(0.85, 0.4))
	plt.show()

	pdf = PdfPages('./imgs/anormaly_cmp_liftcurve_' + method + '_' + anormaly_name + '.pdf')
	pdf.savefig(fig)
	pdf.close()
	return cmp_srv_load
开发者ID:ephemeral2eternity,项目名称:pyDraw,代码行数:34,代码来源:draw_srv_anomaly_liftchart.py

示例13: plotTime

# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import savefig [as 别名]
def plotTime():
	#Time levels
	pp = PdfPages('time.pdf')
	lev1 = 0
	lev2 = 0
	lev3 = 0
	lev4 = 0
	lev5 = 0
	lev6 = 0
	for time in userTime.keys():
		if len(time) > 0:
			intTime = int(time)
			if intTime < 10:
				lev1 += 1 * userTime[time]
			elif intTime >=10 and intTime < 20:
				lev2 += 1 * userTime[time]
			elif intTime >= 20 and intTime < 30:		
				lev3 += 1 * userTime[time]
			elif intTime >=30 and intTime < 40:		
				lev4 += 1 * userTime[time]
			elif intTime >=40 and intTime < 50:		
				lev5 += 1 * userTime[time]
			else:
				lev6 += 1 * userTime[time]
	labels = '10-', '10-20', '20-30', '30-40', '40-50', '50+'
	sizes = [lev1, lev2, lev3, lev4, lev5, lev6] 		
	colors = ['yellowgreen', 'gold', 'lightskyblue', 'blue', 'lightcoral', 'red']
	plt.figure()
	plt.clf()
	plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True)
	plt.axis('equal')
	pp.savefig()
	pp.close()
开发者ID:davidcmm,项目名称:campinaPulse,代码行数:35,代码来源:analisaUsuarios.py

示例14: _analyze

# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import savefig [as 别名]
def _analyze(recordIdList):
    n_artists = get_n_artists()
    n_days = get_n_days(isX=False, isTrain=False)

    resultDict = dict()
    for recordId in recordIdList:
        resultDict[recordId] = getPredict(recordId)

    pdf = PdfPages('../report/record.pdf')
    for i in range(n_artists):
        fig = plt.figure()
        ax = plt.axes()
        ax.xaxis.set_major_formatter(DateFormatter('%m%d'))
        for recordId in recordIdList:
            result = resultDict[recordId]
            dsList = result[:,1]
            firstDay = datetime.strptime(dsList[0], '%Y%m%d')
            artist_id = result[i*n_days,0]
            xData = np.arange(n_days) + date2num(firstDay)
            yData = result[i*n_days:(i+1)*n_days,2]
            plt.plot_date(xData, yData, fmt='-', label=recordId)
        plt.legend(loc='best', shadow=True)
        plt.xlabel('day')
        plt.ylabel('plays')
        plt.title(artist_id)
        pdf.savefig(fig)
        plt.close()
    pdf.close()
开发者ID:jasonfreak,项目名称:almsc,代码行数:30,代码来源:record.py

示例15: plot_tica_and_clusters

# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import savefig [as 别名]
def plot_tica_and_clusters(component_j, transformed_data, clusterer, lag_time, component_i, label = "dot", active_cluster_ids = [], intermediate_cluster_ids = [], inactive_cluster_ids = [], tica_dir = ""):

	trajs = np.concatenate(transformed_data)
	plt.hexbin(trajs[:,component_i], trajs[:,component_j], bins='log', mincnt=1)
	plt.xlabel("tIC %d" %(component_i + 1))
	plt.ylabel('tIC %d' %(component_j+1))
	centers = clusterer.cluster_centers_
	indices = [j for j in range(0,len(active_cluster_ids),1)]

	for i in [active_cluster_ids[j] for j in indices]:
		center = centers[i,:]
		if label == "dot":
			plt.scatter([center[component_i]],[center[component_j]],  marker='v', c='k', s=10)
		else:
			plt.annotate('%d' %i, xy=(center[component_i],center[component_j]), xytext=(center[component_i], center[component_j]),size=6)
	indices = [j for j in range(0,len(intermediate_cluster_ids),5)]
	for i in [intermediate_cluster_ids[j] for j in indices]:
		center = centers[i,:]
		if label == "dot":
			plt.scatter([center[component_i]],[center[component_j]],  marker='8', c='m', s=10)
		else:
			plt.annotate('%d' %i, xy=(center[component_i],center[component_j]), xytext=(center[component_i], center[component_j]),size=6)
	indices = [j for j in range(0,len(inactive_cluster_ids),5)]
	for i in [inactive_cluster_ids[j] for j in indices]:
		center = centers[i,:]
		if label == "dot":
			plt.scatter([center[component_i]],[center[component_j]],  marker='s', c='w', s=10)
		else:
			plt.annotate('%d' %i, xy=(center[component_i],center[component_j]), xytext=(center[component_i], center[component_j]),size=6)


	pp = PdfPages("%s/c%d_c%d_clusters%d.pdf" %(tica_dir, component_i, component_j, np.shape(centers)[0]))
	pp.savefig()
	pp.close()
	plt.clf()
开发者ID:msultan,项目名称:conformation,代码行数:37,代码来源:analysis.py


注:本文中的matplotlib.backends.backend_pdf.PdfPages.savefig方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。