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


Python FigureCanvasAgg.print_figure方法代码示例

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


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

示例1: lambert_conformal

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_figure [as 别名]
def lambert_conformal(request):
    import matplotlib
    from mpl_toolkits.basemap import Basemap
    import numpy as np
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    
    width = float(request.GET.get('width', 6000000))
    height = float(request.GET.get('height', 4500000))
    lat = float(request.GET.get('lat',-7))
    lon = float(request.GET.get('lon',107))
    true_lat1 = float(request.GET.get('true_lat1',5))
    true_lat2 = float(request.GET.get('true_lat2',5))
    
    m = Basemap(width=width,height=height,
            rsphere=(6378137.00,6356752.3142),\
            resolution=None,projection='lcc',\
            lat_1=true_lat1,lat_2=true_lat2,lat_0=lat,lon_0=lon)
    
    fig = Figure()
    canvas = FigureCanvas(fig)
    m.ax = fig.add_axes([0, 0, 1, 1])
    
    m.drawlsmask(land_color='gray',ocean_color='white',lakes=True)
    m.drawparallels(np.arange(-90.,91.,30.), color='black')
    m.drawmeridians(np.arange(-180.,181.,60.), color='black')
    
    x, y = m(lon, lat)
    m.plot(x, y, 'ro')
    
    response = HttpResponse(content_type='image/png')
    canvas.print_figure(response, dpi=100)
    return response
开发者ID:arifwn,项目名称:AQMWEB,代码行数:35,代码来源:plot.py

示例2: plotSolarRadiationAgainstMonth

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_figure [as 别名]
def plotSolarRadiationAgainstMonth(filename):
    trainRowReader = csv.reader(open(filename, 'rb'), delimiter=',')
    month_most_common_list = []
    Solar_radiation_64_list = []
    for row in trainRowReader:
        month_most_common = row[3]
        Solar_radiation_64 = row[6]
        month_most_common_list.append(month_most_common)
        Solar_radiation_64_list.append(Solar_radiation_64)   
     
    #convert all elements in the list to float while skipping the first element for the 1st element is a description of the field.
    month_most_common_list = [float(i) for i in prepareList(month_most_common_list)[1:] ]
    Solar_radiation_64_list = [float(i) for i in prepareList(Solar_radiation_64_list)[1:] ]

    fig=Figure()
    ax=fig.add_subplot(111)
    title='Scatter Diagram of solar radiation against month of the year'
    ax.set_xlabel('Most common month')
    ax.set_ylabel('Solar Radiation')
    fig.suptitle(title, fontsize=14)
    try:
        ax.scatter(month_most_common_list, Solar_radiation_64_list)
        #it is possible to make other kind of plots e.g bar charts, pie charts, histogram
    except ValueError:
        pass
    canvas = FigureCanvas(fig)
    canvas.print_figure('solarRadMonth.png',dpi=500)
开发者ID:huzichunjohn,项目名称:PyCon2012_Talk,代码行数:29,代码来源:test.py

示例3: save

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_figure [as 别名]
    def save(self, name, log=False, vrange=None):
        if self.imdict['X'].sum() == 0.0 and log:
            warn("can't plot {}, in log mode".format(name), RuntimeWarning,
                 stacklevel=2)
            return
        fig = Figure(figsize=(8,6))
        canvas = FigureCanvas(fig)
        ax = fig.add_subplot(1,1,1)
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", "5%", pad="1.5%")
        if log:
            norm=LogNorm()
        else:
            norm=Normalize()
        if vrange:
            self.imdict['vmin'], self.imdict['vmax'] = vrange
        im = ax.imshow(norm=norm,**self.imdict)
        cb_dict = {'cax':cax}
        if log:
            cb_dict['ticks'] = LogLocator(10, np.arange(0.1,1,0.1))
            cb_dict['format'] = LogFormatterMathtext(10)

        try:
            cb = plt.colorbar(im, **cb_dict)
        except ValueError:
            print self.imdict['X'].sum()
            raise
        ax.set_xlabel(self.x_label, x=0.98, ha='right')
        ax.set_ylabel(self.y_label, y=0.98, ha='right')
        if self.cb_label:
            cb.set_label(self.cb_label, y=0.98, ha='right')
        canvas.print_figure(name, bbox_inches='tight')
开发者ID:dguest,项目名称:susy-analysis,代码行数:34,代码来源:draw.py

示例4: make_1d_plots

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_figure [as 别名]
def make_1d_plots(in_file_name, out_dir, ext, b_eff=0.1, reject='U'):
    textsize=_text_size
    taggers = {}
    with h5py.File(in_file_name, 'r') as in_file:
        for tag in ['gaia', mv1uc_name, 'jfc', 'jfit']:
            taggers[tag] = get_c_vs_u_const_beff(
                in_file, tag, b_eff=b_eff, reject=reject)

    fig = Figure(figsize=_fig_size)
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(1,1,1)
    for tname, (vc, vu) in taggers.items():
        label, color = leg_labels_colors.get(tname, (tname, 'k'))
        ax.plot(vc, vu, label=label, color=color, linewidth=_line_width)
    leg = ax.legend(title='$b$-rejection = {}'.format(1/b_eff),
                    prop={'size':textsize})
    leg.get_title().set_fontsize(textsize)

    setup_1d_ctag_legs(ax, textsize, reject=reject)

    fig.tight_layout(pad=0, h_pad=0, w_pad=0)
    if not isdir(out_dir):
        os.mkdir(out_dir)
    file_name = '{}/{rej}Rej-vs-cEff-brej{}{}'.format(
        out_dir, int(1.0/b_eff), ext, rej=reject.lower())
    canvas.print_figure(file_name, bbox_inches='tight')
开发者ID:dguest,项目名称:tagging-performance,代码行数:28,代码来源:ctaging.py

示例5: _plot_baseline_subtracted

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_figure [as 别名]
    def _plot_baseline_subtracted(self, x, y, raw=True, baseline=True):
        """Plot the baseline-subtracted data"""
        from matplotlib.figure import Figure
        from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas

        figure = Figure()
        canvas = FigureCanvas(figure)
        axes1 = figure.add_subplot(1, 1, 1, axisbg='whitesmoke')

        # Points for fit
        axes1.plot(x, y, 'o', color='deepskyblue', markersize=2, alpha=1, label='Baseline-subtracted data')
        axes1.set_xlabel('time (s)')
        axes1.set_ylabel(r' corr. differential power ($\mu$cal / s)')
        axes1.legend(loc='upper center', bbox_to_anchor=(0.2, 0.95), ncol=1, fancybox=True, shadow=True, markerscale=3,
                     prop={'size': 6})

        if raw:
            axes2 = axes1.twinx()
            axes2.plot(x, self.differential_power, 'o', color='gray', markersize=2, alpha=.3, label='Raw data')
            axes2.set_ylabel(r'raw differential power ($\mu$cal / s)')
            axes2.legend(loc='upper center', bbox_to_anchor=(0.8, 0.95), ncol=1, fancybox=True, shadow=True,
                         markerscale=3,
                         prop={'size': 6})
            if baseline:
                axes2.plot(x, self.baseline_power, '-', color='black', alpha=.3, label='baseline')

        axes1.set_title(self.data_filename)
        canvas.print_figure(self.name + '-subtracted.png', dpi=500)
开发者ID:kyleburke1989,项目名称:bayesian-itc,代码行数:30,代码来源:experiments.py

示例6: plot_normprob

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_figure [as 别名]
def plot_normprob(d, snrs, outroot):
    """ Normal quantile plot compares observed SNR to expectation given frequency of occurrence.
    Includes negative SNRs, too.
    """

    outname = os.path.join(d["workdir"], "plot_" + outroot + "_normprob.png")

    # define norm quantile functions
    Z = lambda quan: n.sqrt(2) * erfinv(2 * quan - 1)
    quan = lambda ntrials, i: (ntrials + 1 / 2.0 - i) / ntrials

    # calc number of trials
    npix = d["npixx"] * d["npixy"]
    if d.has_key("goodintcount"):
        nints = d["goodintcount"]
    else:
        nints = d["nints"]
    ndms = len(d["dmarr"])
    dtfactor = n.sum([1.0 / i for i in d["dtarr"]])  # assumes dedisperse-all algorithm
    ntrials = npix * nints * ndms * dtfactor
    logger.info("Calculating normal probability distribution for npix*nints*ndms*dtfactor = %d" % (ntrials))

    # calc normal quantile
    if len(n.where(snrs > 0)[0]):
        snrsortpos = n.array(sorted(snrs[n.where(snrs > 0)], reverse=True))  # high-res snr
        Zsortpos = n.array([Z(quan(ntrials, j + 1)) for j in range(len(snrsortpos))])
        logger.info("SNR positive range = (%.1f, %.1f)" % (snrsortpos[-1], snrsortpos[0]))
        logger.info("Norm quantile positive range = (%.1f, %.1f)" % (Zsortpos[-1], Zsortpos[0]))

    if len(n.where(snrs < 0)[0]):
        snrsortneg = n.array(sorted(n.abs(snrs[n.where(snrs < 0)]), reverse=True))  # high-res snr
        Zsortneg = n.array([Z(quan(ntrials, j + 1)) for j in range(len(snrsortneg))])
        logger.info("SNR negative range = (%.1f, %.1f)" % (snrsortneg[-1], snrsortneg[0]))
        logger.info("Norm quantile negative range = (%.1f, %.1f)" % (Zsortneg[-1], Zsortneg[0]))

    # plot
    fig3 = plt.Figure(figsize=(10, 10))
    ax3 = fig3.add_subplot(111)
    if len(n.where(snrs < 0)[0]) and len(n.where(snrs > 0)[0]):
        logger.info("Plotting positive and negative cands")
        ax3.plot(snrsortpos, Zsortpos, "k.")
        ax3.plot(snrsortneg, Zsortneg, "kx")
        refl = n.linspace(
            min(snrsortpos.min(), Zsortpos.min(), snrsortneg.min(), Zsortneg.min()),
            max(snrsortpos.max(), Zsortpos.max(), snrsortneg.max(), Zsortneg.max()),
            2,
        )
    elif len(n.where(snrs > 0)[0]):
        logger.info("Plotting positive cands")
        refl = n.linspace(min(snrsortpos.min(), Zsortpos.min()), max(snrsortpos.max(), Zsortpos.max()), 2)
        ax3.plot(snrsortpos, Zsortpos, "k.")
    elif len(n.where(snrs < 0)[0]):
        logger.info("Plotting negative cands")
        refl = n.linspace(min(snrsortneg.min(), Zsortneg.min()), max(snrsortneg.max(), Zsortneg.max()), 2)
        ax3.plot(snrsortneg, Zsortneg, "kx")
    ax3.plot(refl, refl, "k--")
    ax3.set_xlabel("SNR")
    ax3.set_ylabel("Normal quantile SNR")
    canvas = FigureCanvasAgg(fig3)
    canvas.print_figure(outname)
开发者ID:gitter-badger,项目名称:rtpipe,代码行数:62,代码来源:parsecands.py

示例7: draw_ctag_rejrej

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_figure [as 别名]
def draw_ctag_rejrej(in_file, out_dir, ext='.pdf'):
    """
    Basic heatmap of efficiency vs two rejections.
    """
    fig = Figure(figsize=_fig_size)
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(1,1,1)
    ds = in_file['gaia/all']

    eff_array, extent = _get_arr_extent(ds)
    label_rejrej_axes(ax, ds)
    im = ax.imshow(eff_array.T, extent=extent,
                   origin='lower', aspect='auto')
    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.grid(which='both')

    # add_contour(ax,ds)

    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    cb = Colorbar(ax=cax, mappable=im)

    out_name = '{}/rejrej{}'.format(out_dir, ext)
    # ignore complaints about not being able to log scale images
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        canvas.print_figure(out_name, bbox_inches='tight')
开发者ID:dguest,项目名称:tagging-performance,代码行数:30,代码来源:ctaging.py

示例8: plotting

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_figure [as 别名]
def plotting(zic1,comparators):
    """docstring for plotting"""
    from mapping import probe_map
    for key in comparators.keys():
        corr = pearsonr(zic1, comparators[key])
        #the string of correlation stats
        s = 'R = '+str(corr[0])+'\nP = '+str(corr[1])
        # Create a figure with size 6 x 6 inches.
        fig = Figure(figsize=(6,6))
        # Create a canvas and add the figure to it.
        canvas = FigureCanvas(fig)
        # Create a subplot.
        ax = fig.add_subplot(111)
        # Set the title.
        ax.set_title(s,fontsize=10)
        # Set the X Axis label.
        ax.set_xlabel('Samples',fontsize=8)
        # Set the Y Axis label.
        ax.set_ylabel('Normalized Expression',fontsize=8)
        # Display Grid.
        ax.grid(True,linestyle='-',color='0.75')
        # Generate the Scatter Plot.
        ax.plot(range(1,25), zic1, 'go-', label=probe_map['206373_at'])
        ax.plot(range(1,25), comparators[key], 'r^-', label=probe_map[key])
        # add the legend
        ax.legend()
        #ax.text(0.1,max(zic1),s)
        # Save the generated Scatter Plot to a PNG file.
        canvas.print_figure('correlations/'+key+'.png',dpi=500)
开发者ID:Bioinformatics-Support-Unit,项目名称:python-scripts,代码行数:31,代码来源:zic1_correlation.py

示例9: plot_jumps

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_figure [as 别名]
def plot_jumps(stream, datafilename, line_name):
    # L1 and L2 data is collected at a rate of 6.0064028254118895 times per second
    # HF spectra data is collected at a rate of 0.9375005859378663 times per second
    median_stream = ndimage.filters.median_filter(stream, 6.0064028254118895) # smooth with width 1 second of data
    smooth_stream = ndimage.filters.gaussian_filter1d(median_stream, 1.0) # smooth
    combined_jumps = find_jumps(stream)
    stream_time_length = (stream.index[-1] - stream.index[0]).total_seconds()
    n_plot_rows = int(np.ceil(stream_time_length/1800.))
    fig, axes = plt.subplots(n_plot_rows, 1, figsize=(40,n_plot_rows*5))
    for n in range(n_plot_rows):
        stream_time_start = stream.index[0] + timedelta(seconds=1800*n)
        stream_time_end = stream.index[0] + timedelta(seconds=1800*(n+1))
        stream_trimmed_values = smooth_stream[(stream.index>stream_time_start) & (stream.index<stream_time_end)]
        stream_trimmed_timeticks = stream.index[(stream.index>stream_time_start)&(stream.index<stream_time_end)]
        axes[n].plot(stream_trimmed_timeticks, stream_trimmed_values, c="purple", lw=2)
        for jump in combined_jumps:
            if jump[2][1] > stream_time_start and jump[2][0] < stream_time_end:
                axes[n].plot([jump[2][1], jump[2][1]], [0, 1000+jump[1][0]], color="red")
                axes[n].text(jump[2][1], 1000+jump[1][0], str(int(round(jump[1][0]))) + " +/- " + str(round(jump[1][1],2)), rotation=45, va="bottom", ha="left")
        axes[n].set_ylim(10,4000)
        axes[n].set_xlim(stream_time_start, stream_time_end)
        axes[n].set_ylabel("Line Amplitude")
        axes[n].set_xlabel("Timestamp")
    canvas = FigureCanvas(fig)
    canvas.print_figure("full_plots/" + datafilename.split(".")[0] + "_" + line_name + "_jumps.png", dpi=72, bbox_inches='tight')
    close("all")
开发者ID:JesseLivezey,项目名称:appliancescience,代码行数:28,代码来源:identify_appliances.py

示例10: plot_nonlinear_iterations

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_figure [as 别名]
def plot_nonlinear_iterations(**kwargs):

    steps = extract_steps(**kwargs)
    
    fig = Figure()
    ax = fig.add_subplot(111)
    title = fig.suptitle(kwargs.get('title'), fontsize = 14, fontweight = 'bold')
    canvas = FigureCanvas(fig)

    step_numbers = [
        step.step_number for step in steps if step.status_convergence == 1]

    num_iters_nonlinear = [
        step.num_iters_nonlinear for step in steps if step.status_convergence == 1]

    ax.bar(
        step_numbers,
        num_iters_nonlinear)

    ax.set_xlabel('Continuation Step')
    ax.set_ylabel('Nonlinear Iterations')

    set_num_ticks(ax, integer = (True, True))

    canvas.print_figure(
        'nonlinear_iterations.pdf',
        bbox_extra_artists = [title],
        bbox_inches = 'tight')
开发者ID:gahansen,项目名称:Albany,代码行数:30,代码来源:plot_data_run.py

示例11: draw_plot

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_figure [as 别名]
def draw_plot(meta, data1, data2, fn):
	"""
	
	"""
	

	fig = Figure(figsize = (10,10))
	axis = fig.add_subplot(1,1,1)
	axis.set_title(meta)
	axis.set_xlabel("MLOD")
	axis.set_ylabel("Markers")
	axis.grid(False)
	axis.autoscale(enable = True)	
	axis.axhline(0, color = 'k')	
	
	x = [info[0] for info in data1]
	y = [info[2] for info in data1]	
	axis.plot(x, y, color='r', label = 'sse')
	
	x = [info[0] for info in data2]
	y = [info[2] for info in data2]	
	axis.plot(x, y, color='b', label = 'gxe')
	
	box = axis.get_position()
	axis.set_position([box.x0, box.y0, box.width * 0.8, box.height])
	
	axis.legend(loc = 'center left', bbox_to_anchor=(1.0,0.5))
	
	canvas = FigureCanvas(fig)
	print "Saving file..."
	canvas.print_figure(fn)
开发者ID:schoothubber,项目名称:qtl_project,代码行数:33,代码来源:metabolite_mQTL.py

示例12: graph

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_figure [as 别名]
def graph(args):
  # Get data points
  f = open("%s/http-data.txt" % (args.dir, ))
  data = map(lambda x: x.split(','), f.readlines())
  f.close()
  xdata = map(lambda x: float(x[0]), data)
  ydata = map(lambda x: float(x[1]), data)

  # Create a figure with size 6 x 6 inches.
  fig = Figure(figsize=(6, 6))

  # Create a canvas and add the figure to it.
  canvas = FigureCanvas(fig)

  # Added various information
  ax = fig.add_subplot(111)
  ax.set_title("Impact on HTTP Flows", fontsize=14)
  ax.set_xlabel("File Size (packets)", fontsize=12)
  ax.set_ylabel("Response Time (Normalized)", fontsize=12)
  ax.set_xscale('log')
  ax.set_yscale('log')

  # Display Grid.
  ax.grid(True, linestyle='-', color='0.75')

  # Generate and save the Scatter Plot.
  ax.scatter(xdata, ydata, s=20, color='tomato');
  canvas.print_figure(args.out, dpi=500)
开发者ID:carriercomm,项目名称:TCPDoS,代码行数:30,代码来源:plot-http.py

示例13: plot_ast_fields

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_figure [as 别名]
def plot_ast_fields(fields, matches, ast_centers=None):
    fig = Figure(figsize=(3.5, 3.5), frameon=False)
    canvas = FigureCanvas(fig)
    gs = gridspec.GridSpec(1, 1,
                           left=0.15, right=0.95, bottom=0.15, top=0.95,
                           wspace=None, hspace=None,
                           width_ratios=None, height_ratios=None)
    basemap = load_galex_map()
    ax = setup_galex_axes(fig, gs[0], basemap)
    plot_patch_footprints(ax, alpha=0.8, edgecolor='dodgerblue')
    for n, m in matches.iteritems():
        footprint = np.array(m['poly'])
        patch = Polygon(footprint, closed=True,
                        transform=ax.get_transform('world'),
                        facecolor='y', alpha=1,
                        edgecolor='k', lw=0.5, zorder=10)
        ax.add_patch(patch)
        x = footprint[:, 0].mean()
        y = footprint[:, 1].mean()
        ax.annotate('{0:d}'.format(n), xy=(x, y),
                    xycoords=ax.get_transform('world'),
                    xytext=(3, -3), textcoords="offset points",
                    size=8,
                    bbox=dict(boxstyle="round",
                              fc=(1., 1., 1., 0.8),
                              edgecolor='None'))
    if ast_centers is not None:
        ax.scatter(ast_centers[:, 0], ast_centers[:, 1],
                   marker='*', c='y',
                   transform=ax.get_transform('world'))
    gs.tight_layout(fig, pad=1.08, h_pad=None, w_pad=None, rect=None)
    ax.coords[0].ticklabels.set_size(11)
    ax.coords[1].ticklabels.set_size(11)
    canvas.print_figure("phat_ast_fields.pdf", format="pdf")
开发者ID:jonathansick,项目名称:androcmd,代码行数:36,代码来源:match_phat_ast_fields.py

示例14: draw_pt_bins

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_figure [as 别名]
def draw_pt_bins(in_file, out_dir, eff=0.7, rej_flavor='U', ext='.pdf', 
                 subset=None): 
    fig = Figure(figsize=(8,6))
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(1,1,1)
    ax.grid(which='both')
    ax.set_xscale('log')
    for tagger in tagschema.get_taggers(in_file, subset): 
        pt_bins = tagschema.get_pt_bins(in_file['B/btag/ptBins'])
        eff_group = in_file['B/btag/ptBins']
        rej_group = in_file['{}/btag/ptBins'.format(rej_flavor.upper())]
        x_vals, y_vals, x_err, y_err = _get_pt_xy(
            eff_group, rej_group, pt_bins, eff, tagger=tagger)
        with tagschema.ColorScheme('colors.yml') as colors: 
            ax.errorbar(
                x_vals, y_vals, label=tagger, #xerr=x_err, 
                yerr=y_err, color=colors[tagger])
    ax.legend(numpoints=1, loc='upper left')
    ax.set_xlim(20, np.max(x_vals) * 1.1)
    ax.set_xlabel('$p_{\mathrm{T}}$ [GeV]', x=0.98, ha='right')
    ax.set_ylabel(rej_label(rej_flavor, eff), y=0.98, ha='right')
    x_formatter = FuncFormatter(tick_format)
    ax.xaxis.set_minor_formatter(x_formatter)
    ax.xaxis.set_major_formatter(x_formatter)
    out_name = '{}/{}Rej{}_ptbins{}'.format(
        out_dir, rej_flavor.lower(), int(eff*100), ext)
    canvas.print_figure(out_name, bbox_inches='tight')
开发者ID:lukedeo,项目名称:tagging-performance,代码行数:29,代码来源:tagpt.py

示例15: generateChart

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_figure [as 别名]
    def generateChart(self):
        u_genes = self.getUniqueGenes()
        data = dict()
        for gene, tags in u_genes.iteritems():
            if not data.has_key(len(tags)):
                data[len(tags)] = 0
            data[len(tags)] += 1
        data[0] = self._genes_c - len(u_genes.keys())

        xs = list()
        ys = list()
        # Convert the values to %
        for k, v in data.iteritems():
            xs.append(k)
            ys.append((float(v) / self._genes_c))

        fig = Figure()
        ax = fig.add_subplot(111)
        ax.bar(xs, ys, width=0.5, align='center')
        fig.get_axes()[0].set_ylabel('% of genes')
        fig.get_axes()[0].set_xlabel('# of unique tags')
        #fig.get_axes()[0].set_yscale('log')
        canvas = FigureCanvasAgg(fig)
        canvas.print_figure('enzyme-%s-length-%i.png' % \
                            (self.enzyme, self._original_tag_length),
                            dpi=96)
        return data
开发者ID:kaelfischer,项目名称:lib_prrsv,代码行数:29,代码来源:pmageEnzyme.py


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