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


Python backend_agg.FigureCanvasAgg类代码示例

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


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

示例1: __get_column_width

 def __get_column_width(self):
 
   max_length = 0
   max_column_text = ''
   flag = self.prefs.get('legend_numbers',True)
   unit = self.prefs.get('legend_unit',False)
   for label,num in self.labels:      
     if not flag: num = None
     if num is not None:
       column_length = len(str(label)+str(num)) + 1
     else:
       column_length = len(str(label)) + 1  
     if column_length > max_length:
       max_length = column_length
       if flag:
         if type(num) == types.IntType or type(num) == types.LongType:
           numString = str(num)
         else:
           numString = "%.1f" % float(num)  
         max_column_text = '%s  %s' % (str(label),numString)
         if unit:
           max_column_text += "%"
       else:
         max_column_text = '%s   ' % str(label)  
                        
   figure = Figure()   
   canvas = FigureCanvasAgg(figure) 
   dpi = self.prefs['dpi']
   figure.set_dpi( dpi ) 
   l_size,l_padding = self.__get_legend_text_size()    
   self.text_size = pixelToPoint(l_size,dpi)           
   text = Text(0.,0.,text=max_column_text,size=self.text_size)
   text.set_figure(figure)
   bbox = text.get_window_extent(canvas.get_renderer())
   self.column_width = bbox.width+6*l_size
开发者ID:DIRACGrid-test,项目名称:DIRAC,代码行数:35,代码来源:Legend.py

示例2: figure_to_response

def figure_to_response(f):
    """ Creates a png image to be displayed in an html file """
    canvas = FigureCanvasAgg(f)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    matplotlib.pyplot.close(f)
    return response
开发者ID:dmalone,项目名称:tacc_stats,代码行数:7,代码来源:views.py

示例3: startup_cost

def startup_cost():
    import datetime
    import StringIO
    import random
    import base64

    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    from matplotlib.dates import DateFormatter

    fig=Figure(facecolor='#ffffff')
    ax=fig.add_subplot(211)
    ax2=fig.add_subplot(212, axisbg='y')
    x=[]
    y=[]
    now=datetime.datetime.now()
    delta=datetime.timedelta(days=1)
    for i in range(10):
        x.append(now)
        now+=delta
        y.append(random.randint(0, 1000))
    ax.plot_date(x, y, '-')
    ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
    ax2.plot_date(x, y, '-')
    ax2.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
    fig.autofmt_xdate()
    canvas=FigureCanvas(fig)
    png_output = StringIO.StringIO()
    canvas.print_png(png_output)
    image=make_response(png_output.getvalue())
    response.headers['Content-Type'] = 'image/png'
    return response
开发者ID:rlundquist3,项目名称:colony.farm,代码行数:32,代码来源:startup_cost_2.py

示例4: plot_lm

def plot_lm(d, snrs, l1s, m1s, outroot):
    """ Plot the lm coordinates (relative to phase center) for all candidates.
    """

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

    snrmin = 0.8 * min(d["sigma_image1"], d["sigma_image2"])
    fig4 = plt.Figure(figsize=(10, 10))
    ax4 = fig4.add_subplot(111)

    # plot positive
    good = n.where(snrs > 0)
    sizes = (snrs[good] - snrmin) ** 5  # set scaling to give nice visual sense of SNR
    xarr = 60 * n.degrees(l1s[good])
    yarr = 60 * n.degrees(m1s[good])
    ax4.scatter(xarr, yarr, s=sizes, facecolor="none", alpha=0.5, clip_on=False)
    # plot negative
    good = n.where(snrs < 0)
    sizes = (n.abs(snrs[good]) - snrmin) ** 5  # set scaling to give nice visual sense of SNR
    xarr = 60 * n.degrees(l1s[good])
    yarr = 60 * n.degrees(m1s[good])
    ax4.scatter(xarr, yarr, s=sizes, marker="x", edgecolors="k", alpha=0.5, clip_on=False)

    ax4.set_xlabel("Dec Offset (amin)")
    ax4.set_ylabel("RA Offset (amin)")
    fov = n.degrees(1.0 / d["uvres"]) * 60.0
    ax4.set_xlim(fov / 2, -fov / 2)
    ax4.set_ylim(-fov / 2, fov / 2)
    canvas4 = FigureCanvasAgg(fig4)
    canvas4.print_figure(outname)
开发者ID:gitter-badger,项目名称:rtpipe,代码行数:30,代码来源:parsecands.py

示例5: plot_normprob

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,代码行数:60,代码来源:parsecands.py

示例6: simple

def simple():
    import datetime
    import StringIO
    import random

    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    from matplotlib.dates import DateFormatter

    fig=Figure()
    ax=fig.add_subplot(111)
    x=[]
    y=[]
    now=datetime.datetime.now()
    delta=datetime.timedelta(days=1)
    for i in range(10):
        x.append(now)
        now+=delta
        y.append(random.randint(0, 1000))
    ax.plot_date(x, y, '-')
    ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
    fig.autofmt_xdate()
    canvas=FigureCanvas(fig)
    png_output = StringIO.StringIO()
    canvas.print_png(png_output)
    data = png_output.getvalue().encode('base64')
    data_url = 'data:image/png;base64,{}'.format(urllib.quote(data.rstrip('\n')))
    response=make_response(png_output.getvalue())
    response.headers['Content-Type'] = 'image/png'
    return response
开发者ID:crystal95,项目名称:Timelabs_Project,代码行数:30,代码来源:app3D_online.py

示例7: draw

 def draw(self):
     """
     Draw the figure using the agg renderer
     """
     self.canvas.clear()
     FigureCanvasAgg.draw(self)
     if self.blitbox is None:
         l, b, w, h = self.figure.bbox.bounds
         w, h = int(w), int(h)
         buf_rgba = self.get_renderer().buffer_rgba()
     else:
         bbox = self.blitbox
         l, b, r, t = bbox.extents
         w = int(r) - int(l)
         h = int(t) - int(b)
         t = int(b) + h
         reg = self.copy_from_bbox(bbox)
         buf_rgba = reg.to_string()
     texture = Texture.create(size=(w, h))
     texture.flip_vertical()
     with self.canvas:
         Color(1.0, 1.0, 1.0, 1.0)
         self.img_rect = Rectangle(texture=texture, pos=self.pos, size=(w, h))
     texture.blit_buffer(bytes(buf_rgba), colorfmt="rgba", bufferfmt="ubyte")
     self.img_texture = texture
开发者ID:jonatanolofsson,项目名称:garden.matplotlib,代码行数:25,代码来源:backend_kivyagg.py

示例8: _plot_baseline_subtracted

    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,代码行数:28,代码来源:experiments.py

示例9: save_plotSpectrum

def save_plotSpectrum(y,Fs,image_name):
    """
    Plots a Single-Sided Amplitude Spectrum of y(t)
    """
    fig = Figure(linewidth=0.0)
    fig.set_size_inches(fig_width,fig_length, forward=True)
    Figure.subplots_adjust(fig, left = fig_left, right = fig_right, bottom = fig_bottom, top = fig_top, hspace = fig_hspace)
    n = len(y) # length of the signal

    _subplot = fig.add_subplot(2,1,1)        
    print "Fi"
    _subplot.plot(arange(0,n),y)
    xlabel('Time')
    ylabel('Amplitude')
    _subploti_2=fig.add_subplot(2,1,2)
    k = arange(n)
    T = n/Fs
    frq = k/T # two sides frequency range
    frq = frq[range(n/2)] # one side frequency range

    Y = fft(y)/n # fft computing and normalization
    Y = Y[range(n/2)]

    _subplot_2.plot(frq,abs(Y),'r') # plotting the spectrum
    xlabel('Freq (Hz)')
    ylabel('|Y(freq)|')
    print "here"
    canvas = FigureCanvasAgg(fig)
    if '.eps' in outfile_name:
        canvas.print_eps(outfile_name, dpi = 110)
    if '.png' in outfile_name:
        canvas.print_figure(outfile_name, dpi = 110)
开发者ID:FomkaV,项目名称:wifi-arsenal,代码行数:32,代码来源:non_wifi_interference_analysis.py

示例10: team_wp

def team_wp(request, manager):    
    manager = manager.replace('-', ' ')
    try:
        team = Team.objects.get(manager__iexact=manager)
    except Team.DoesNotExist:
        raise Http404()
    
    week = WeekPoints.objects.latest_week()
    
    points = team.weekly_points.values_list('points', flat=True)
    weeks = range(1, week + 1)
    
    teams = list(WeekPoints.objects.values_list('points', flat=True))
    shape = (Team.objects.count(), week)
    avgs = mean(reshape(array(teams), shape), axis=0)
    
    fig = Figure(figsize=(7, 3), dpi=100, facecolor='white')
    ax = fig.add_subplot(111)
    rects = ax.bar(weeks, points, align='center', linewidth=1, color='#008ad1', width=1)
    ax.set_xlabel("Week")
    ax.set_ylabel("Points")
    ax.set_xticks(weeks) # add a tick for every week
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width() / 2., height / 2., str(height),
                fontsize=10, color="#ffffff", ha='center')
    ax.set_xlim((0.5, max(10, week) + 0.5))
    ax.plot(weeks, avgs, color='blue', marker='*', label='Week average score')
    ax.legend(markerscale=0, handlelength=3)

    canvas = FigureCanvas(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
开发者ID:LS80,项目名称:FFL,代码行数:34,代码来源:views.py

示例11: payee_boxplot

def payee_boxplot(request, payee):

    data_parameters = ytd + ['-w', '-E', '-F', '%(amount)\n', '-M', 'reg', 'Expenses', 'and', 'payee', payee]

    output = runledger(data_parameters)
    values = [float(sanatize(line)) for line in output.split('\n') if line != ""]
    if(len(values) <= 0): values.append(0)

    fig = plt.figure()
    ax = fig.add_subplot(111)

    boxplot(values)

    title('Boxplot of ' + payee)
    ax.yaxis.set_major_formatter(moneyFmt)
    ax.format_ydata = price

    ax.set_xticklabels([prettyname(payee)])
    ax.set_ylim(min(values + [-1.0]) * 1.1, max(values + [1.0]) * 1.1)

    fig.autofmt_xdate()


    canvas=FigureCanvas(fig)
    response=HttpResponse(content_type='image/png')
    canvas.print_png(response)
    plt.close(fig)

    return response
开发者ID:bettse,项目名称:pygl,代码行数:29,代码来源:charts.py

示例12: getImage

    def getImage(self):
        ddict=self.fitresult
        try:
            fig = Figure(figsize=(6,3)) # in inches
            canvas = FigureCanvas(fig)
            ax = fig.add_axes([.15, .15, .8, .8])
            ax.set_axisbelow(True)
            logplot = self.plotDict.get('logy', True)
            if logplot:
                axplot = ax.semilogy
            else:
                axplot = ax.plot
            axplot(ddict['result']['energy'], ddict['result']['ydata'], 'k', lw=1.5)
            axplot(ddict['result']['energy'], ddict['result']['continuum'], 'g', lw=1.5)
            legendlist = ['spectrum', 'continuum', 'fit']
            axplot(ddict['result']['energy'], ddict['result']['yfit'], 'r', lw=1.5)
            fontproperties = FontProperties(size=8)
            if ddict['result']['config']['fit']['sumflag']:
                axplot(ddict['result']['energy'],
                       ddict['result']['pileup'] + ddict['result']['continuum'], 'y', lw=1.5)
                legendlist.append('pileup')
            if matplotlib_version < '0.99.0':
                legend = ax.legend(legendlist,0,
                                   prop = fontproperties, labelsep=0.02)
            else:
                legend = ax.legend(legendlist,0,
                                   prop = fontproperties, labelspacing=0.02)
        except ValueError:
            fig = Figure(figsize=(6,3)) # in inches
            canvas = FigureCanvas(fig)
            ax = fig.add_axes([.15, .15, .8, .8])
            ax.set_axisbelow(True)
            ax.plot(ddict['result']['energy'], ddict['result']['ydata'], 'k', lw=1.5)
            ax.plot(ddict['result']['energy'], ddict['result']['continuum'], 'g', lw=1.5)
            legendlist = ['spectrum', 'continuum', 'fit']
            ax.plot(ddict['result']['energy'], ddict['result']['yfit'], 'r', lw=1.5)
            fontproperties = FontProperties(size=8)
            if ddict['result']['config']['fit']['sumflag']:
                ax.plot(ddict['result']['energy'],
                            ddict['result']['pileup'] + ddict['result']['continuum'], 'y', lw=1.5)
                legendlist.append('pileup')
            if matplotlib_version < '0.99.0':
                legend = ax.legend(legendlist,0,
                               prop = fontproperties, labelsep=0.02)
            else:
                legend = ax.legend(legendlist,0,
                               prop = fontproperties, labelspacing=0.02)

        ax.set_xlabel('Energy')
        ax.set_ylabel('Counts')
        legend.draw_frame(False)

        outfile = self.outdir+"/"+self.outfile+".png"
        try:
            os.remove(outfile)
        except:
            pass

        canvas.print_figure(outfile)
        return self.__getFitImage(self.outfile+".png")
开发者ID:alemirone,项目名称:pymca,代码行数:60,代码来源:QtMcaAdvancedFitReport.py

示例13: save

    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,代码行数:32,代码来源:draw.py

示例14: plot_activity

def plot_activity(values):

	daysFmt = DateFormatter("%d-%B %H:00")

	fig=Figure()
	ax=fig.add_subplot(111)

	times = values.keys()
	times.sort()

	number_found = [values[key] for key in times]

	ax.plot_date(times, number_found, '-')
	
	#assert 0, '%s'%(values)

	# format the ticks
	ax.xaxis.set_major_locator(HourLocator(byhour=range(0,24,4)))
	ax.xaxis.set_major_formatter(daysFmt)
	ax.autoscale_view()
	ax.grid(True)
	ax.set_title('All devices')

	fig.autofmt_xdate()
	canvas=FigureCanvas(fig)
	response=HttpResponse(content_type='image/png')
	canvas.print_png(response)
	return response
开发者ID:sbeering,项目名称:METR4900StephenEndicott,代码行数:28,代码来源:plot.py

示例15: draw_simple_rejrej

def draw_simple_rejrej(in_file, out_dir, ext='.pdf', tagger='gaia',
                       official=False, approval='Internal', points=[]):
    """
    Draw iso-efficiency contours for one tagger (no colors).
    """
    fig = Figure(figsize=_fig_size)
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(1,1,1)
    ds = in_file[tagger + '/all']

    label_rejrej_axes(ax, ds)
    levels = np.linspace(0.2, 0.5, 7)
    add_contour(ax, ds, opts=dict(levels=levels, textsize=10))
    zax = long_particle_names[ds.attrs['xyz'][2]]
    if official:
        _add_rejrej_official(ax, approval, zax=zax, size=9)

    for y, x, z in points:
        ax.scatter(x, y, s=20, c='yellow')
        ax.annotate(
            r'$\epsilon_{{c}}$ = {:.2f}'.format(z), (x,y), xytext=(-8,0),
            textcoords='offset points', size='x-small',
            bbox = dict(boxstyle = 'round', fc = 'yellow', alpha = 1),
            # arrowprops = dict(arrowstyle = '->'),
            ha='right', va='top')

    out_name = '{}/rejrej-simple{}'.format(out_dir, ext)
    canvas.print_figure(out_name, bbox_inches='tight')
开发者ID:dguest,项目名称:tagging-performance,代码行数:28,代码来源:ctaging.py


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