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


Python FigureCanvasAgg.print_png方法代码示例

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


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

示例1: category_bar_charts

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_png [as 别名]
def category_bar_charts():
    sns.set(style="whitegrid")
    sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5})
    f, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 7), sharex=False)

    retirement_sums = sorted(retirement_class_sums(), reverse=True)
    x = [a[1] for a in retirement_sums]
    y = [a[0] for a in retirement_sums]
    sns.barplot(x, y, palette="YlOrRd_d", ax=ax1)
    ax1.set_ylabel("By Category")

    account_type_sums = sorted(account_by_type_sums(), reverse=True)
    x = [a[1] for a in account_type_sums]
    y = [a[0] for a in account_type_sums]
    sns.barplot(x, y, palette="BuGn_d", ax=ax2)
    ax2.set_ylabel("By Category")

    account_owner_sums = sorted(account_by_owner_sums(), reverse=True)
    x = [a[1] for a in account_owner_sums]
    y = [a[0] for a in account_owner_sums]
    sns.barplot(x, y, palette="Blues_d", ax=ax3)
    ax3.set_ylabel("By Owner")

    sns.despine(left=True)
    f.tight_layout()
    canvas = FigureCanvas(plt.gcf())
    png_output = io.BytesIO()
    canvas.print_png(png_output)
    response=make_response(png_output.getvalue())
    response.headers['Content-Type'] = 'image/png'
    return response
开发者ID:ezetter,项目名称:ez_portfolio_manager,代码行数:33,代码来源:charts.py

示例2: graph_prices

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_png [as 别名]
def graph_prices(x, y, gname):
    
    '''make a plot of the prices over time for a specific game'
    x is be the dates of the bins
    y is the prices
    gname is the name of the game
    '''
    x_list = list(x)
    x_dt =  [datetime.fromtimestamp(xx) for xx in x_list]
    fig=Figure(facecolor='white')
    ax=fig.add_subplot(111)
    ax.plot(x_dt,y,'r-')    
    ax.set_ylim([0,np.max(y) + np.max(y) * 0.10])
    #ax.set_title(gname)
    #ax.set_axis_bgcolor('red')

    formatter = FuncFormatter(money_format)
    ax.yaxis.set_major_formatter(formatter)
    #fig.autofmt_xdate()
    #xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S')
    #ax.xaxis.set_major_formatter(xfmt)
    ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
    fig.autofmt_xdate()
    
    canvas=FigureCanvas(fig)
    png_output = StringIO.StringIO()
    canvas.print_png(png_output)
    response=make_response(png_output.getvalue())
    response.headers['Content-Type'] = 'image/png'
    return response
开发者ID:rbrackney,项目名称:steamsaleforecaster,代码行数:32,代码来源:a_Model.py

示例3: plot

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_png [as 别名]
def plot(title='title',xlab='x',ylab='y',mode='plot',
         data={'xxx':[(0,0),(1,1),(1,2),(3,3)],
               'yyy':[(0,0,.2,.2),(2,1,0.2,0.2),(2,2,0.2,0.2),(3,3,0.2,0.3)]}):
    fig=Figure()
    fig.set_facecolor('white')
    ax=fig.add_subplot(111)
    if title: ax.set_title(title)
    if xlab: ax.set_xlabel(xlab)
    if ylab: ax.set_ylabel(ylab)
    legend=[]
    keys=sorted(data)
    for key in keys:
        stream = data[key]
        (x,y)=([],[])
        for point in stream:
            x.append(point[0])
            y.append(point[1])
        if mode=='plot':
            ell=ax.plot(x, y)
            legend.append((ell,key))
        if mode=='hist':
            ell=ax.hist(y,20)            
    if legend:
        ax.legend([x for (x,y) in legend], [y for (x,y) in legend], 
                  'upper right', shadow=True)
    canvas=FigureCanvas(fig)
    stream=cStringIO.StringIO()
    canvas.print_png(stream)
    return stream.getvalue()
开发者ID:PrashantYadav,项目名称:IPUanalytics,代码行数:31,代码来源:plotimage.py

示例4: plot_activity

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_png [as 别名]
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,代码行数:30,代码来源:plot.py

示例5: figure_to_response

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_png [as 别名]
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,代码行数:9,代码来源:views.py

示例6: bar_plot

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_png [as 别名]
def bar_plot(d, labels):
    colors = itertools.cycle(['b', 'g', 'r', 'c', 'm', 'y', 'k'])
    fig=Figure(figsize=(8, 6), dpi=200)
    fig.set_facecolor('white')
    fig.subplots_adjust(bottom=0.30)
    ax=fig.add_subplot(111)
    ax.set_title("")
    ax.set_ylabel('Factor values')
    #ax.grid(which='major')
    bottom = None
    for col in d.columns:
	if bottom is None:
	    bottom = 0*d[col]
	ax.bar(range(len(d[col])), d[col], align='center', bottom=bottom,
		label=labels[col], color=colors.next(), alpha=0.6)
	bottom += d[col]
    ax.set_xticks(range(len(d[col])))
    ax.set_xlim([-0.5, len(d[col])])
    ax.set_xticklabels([unicode(el) for el in d[col].index], size='x-small',
	    rotation='vertical')
    leg = ax.legend(loc='best', fancybox=True, prop={'size':9})
    leg.get_frame().set_alpha(0.5)

    canvas=FigureCanvas(fig)
    stream=cStringIO.StringIO()
    canvas.print_png(stream, bbox_inches='tight')
    return stream.getvalue()
开发者ID:b2b-ray,项目名称:multifactor_analysis,代码行数:29,代码来源:plot.py

示例7: plot_demo

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_png [as 别名]
def plot_demo():
    import numpy as np
    import matplotlib
    matplotlib.use('Agg')
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    import matplotlib.mlab as mlab
    import matplotlib.pyplot as plt

    mu, sigma = 100, 15
    x = mu + sigma*np.random.randn(10000)

    # the histogram of the data
    n, bins, patches = plt.hist(x, 50, normed=1, facecolor='green', alpha=0.75)

    # add a 'best fit' line
    y = mlab.normpdf( bins, mu, sigma)
    l = plt.plot(bins, y, 'r--', linewidth=1)

    plt.xlabel('Smarts')
    plt.ylabel('Probability')
    plt.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$')
    plt.axis([40, 160, 0, 0.03])
    plt.grid(True)

    # Write to the canvas
    fig = plt.gcf()
    fig.set_size_inches(6,5)
    canvas = FigureCanvas(fig)
    output = StringIO.StringIO()
    canvas.print_png(output)
    response = make_response(output.getvalue())
    response.mimetype = 'image/png'
    return response
开发者ID:AdityoSanjaya,项目名称:Data-Science-45min-Intros,代码行数:36,代码来源:coin_toss.py

示例8: simple

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_png [as 别名]
def simple(request):
    import random
    import django
    import datetime

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

    fig = Figure(figsize=(5, 5), dpi=80)
    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)
    response = django.http.HttpResponse(content_type="image/png")
    canvas.print_png(response)
    return response
开发者ID:grlbrwrg,项目名称:FAB3Lab,代码行数:28,代码来源:views.py

示例9: get

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_png [as 别名]
    def get(self, req, *args, **kwargs):
        json = 'application/json' in req.META.get('HTTP_ACCEPT')
        if not json and not Figure:
            raise Http404("Can't generate image")

        context = self.get_context_data(**kwargs)
        data = self.data_from_context(context)

        if json:
            # convert to list of lists
            data[:,0] = num2epoch(data[:,0])
            data[:,0] *= 1000 # to ms

            ret = [None]*data.shape[0]
            for i in range(data.shape[0]):
                ret[i] = list(data[i,:])

            return JsonResponse({'data':ret})

        tz = get_current_timezone()

        fig = Figure(dpi=96, figsize=(4,3))
        ax = fig.add_subplot(111)
        ax.plot_date(data[:,0], data[:,1])
        ax.set(**self.set_axis)
        ax.xaxis.set_major_formatter(DateFormatter('%H:%M:%S', tz=tz))
        fig.autofmt_xdate()
        canva = FigureCanvas(fig)

        resp = HttpResponse(content_type='image/png')
        canva.print_png(resp)
        return resp
开发者ID:mdavidsaver,项目名称:caobserver,代码行数:34,代码来源:plot.py

示例10: ScatterPlotData

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_png [as 别名]
def ScatterPlotData(request, GeneticDataRecords, GeneticAttributeNameA, GeneticAttributeNameB, ClusterCutOff, PlotXLabel, PlotYLabel, PlotTitle):
    """ 
    This plotting option is for creating a scatter plot.  
    """
    plt.xlabel(PlotXLabel)
    plt.ylabel(PlotYLabel)
    plt.title(PlotTitle)
    fig = Figure(figsize=[8,8])                               
    ax = fig.add_subplot(1,1,1)
    # A color swtich is added below for any data past the threshold inputted into this method.
    for GeneticAttributeEntry in GeneticDataRecords:
        if (float(getattr(GeneticAttributeEntry, GeneticAttributeNameA)) < float(ClusterCutOff)):
            ax.scatter(float(getattr(GeneticAttributeEntry, GeneticAttributeNameA)),float(getattr(GeneticAttributeEntry, GeneticAttributeNameB)),c="blue")
        else:
            ax.scatter(float(getattr(GeneticAttributeEntry, GeneticAttributeNameA)),float(getattr(GeneticAttributeEntry, GeneticAttributeNameB)),c="red")
    canvas = FigureCanvasAgg(fig)
    ax.set_xlabel(PlotXLabel)
    ax.set_ylabel(PlotYLabel)
    ax.set_title(PlotTitle)

    # write image data to a string buffer and get the PNG image bytes
    buf = cStringIO.StringIO()
    canvas.print_png(buf)
    data = buf.getvalue()
    
    img = Image.open(StringIO.StringIO(data))
    response = HttpResponse(mimetype="image/png")
    img.save(response, 'PNG')

    return (response)
开发者ID:nmsutton,项目名称:GeneticsAnalyzer,代码行数:32,代码来源:GeneratePlot.py

示例11: PlotData

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_png [as 别名]
def PlotData(request, GeneticDataRecords, GeneticAttributeName, PlotXLabel, PlotYLabel, PlotTitle):
    """
    This is the standard genetic module plotting option and a histogram is created.  The plot is written to
    a string buffer and later rendered as a png image which is returned in a html response.  The image is not
    needed to be saved as a file in the hard disk each time it is created.
    """
    AttributeGroupGeneticDataRecords = []
    for RecordEntry in GeneticDataRecords:
        AttributeGroupGeneticDataRecords.append(float(getattr(RecordEntry, GeneticAttributeName)))

    plt.xlabel(PlotXLabel)
    plt.ylabel(PlotYLabel)
    plt.title(PlotTitle)
    fig = Figure(figsize=[8,8])                               
    ax = fig.add_subplot(1,1,1)
    ax.hist(AttributeGroupGeneticDataRecords, 23, normed=1, facecolor='green', alpha=0.75)
    canvas = FigureCanvasAgg(fig)
    ax.set_xlabel(PlotXLabel)
    ax.set_ylabel(PlotYLabel)
    ax.set_title(PlotTitle)

    # write image data to a string buffer and get the PNG image bytes
    buf = cStringIO.StringIO()
    canvas.print_png(buf)
    data = buf.getvalue()
    
    img = Image.open(StringIO.StringIO(data))
    response = HttpResponse(mimetype="image/png")
    img.save(response, 'PNG')

    return (response)
开发者ID:nmsutton,项目名称:GeneticsAnalyzer,代码行数:33,代码来源:GeneratePlot.py

示例12: searchstringPieChart

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_png [as 别名]
def searchstringPieChart(request):
    page_title='Search String Pie Chart'
    year=stat.getYear()
    searchList = list(SearchTerm.objects.values_list('q', flat=True))
    search_string = ' '.join(searchList)
    result = Counter(search_string.split()).most_common(10)
    searchDict = {}
    for key,val in result:
        searchDict[key] = val

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

    title='Top Ten search string submitted by user ({0})'.format(year)
    fig.suptitle(title, fontsize=14)
    try:
        x = searchDict.values()
        labels = searchDict.keys()
        ax.pie(x, labels=labels);
    except 	ValueError:
        pass
    canvas = FigureCanvas(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
开发者ID:huzichunjohn,项目名称:PyCon2012_Talk,代码行数:27,代码来源:views.py

示例13: displayrankedItemwithBidsPieChart

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_png [as 别名]
def displayrankedItemwithBidsPieChart(request):
    page_title='Pie Chart on Ranked Item'
    year=stat.getYear()
    itemBidDict, bidtotalSum = stat.createItemIDBidCountDict()
    top_ten_dict = stat.sortedItemDictionary(itemBidDict)
    itemobjDict = {}	
    for key,value in top_ten_dict:
        itemObj = get_object_or_404(Item, pk=key)
        itemobjDict[itemObj.name] = value

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

    title='Top Ten ranked items with the highest bids ({0})'.format(year)
    fig.suptitle(title, fontsize=14)
    try:
        x = itemobjDict.values()
        labels = itemobjDict.keys()
        ax.pie(x, labels=labels);
    except ValueError:
        pass
    canvas = FigureCanvas(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
开发者ID:huzichunjohn,项目名称:PyCon2012_Talk,代码行数:27,代码来源:views.py

示例14: simple

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_png [as 别名]
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,代码行数:32,代码来源:app3D_online.py

示例15: show_temperature_graph

# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_png [as 别名]
def show_temperature_graph(response, siteLocation=None):
    import random
    import os
    import tempfile
    os.environ['MPLCONFIGDIR'] = tempfile.mkdtemp()
    import django
    import datetime
    
    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)
    response=django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
开发者ID:ewb-ucf,项目名称:weatherStationProject,代码行数:31,代码来源:old_views.py


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