• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python figure.Figure类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: plotSolarRadiationAgainstMonth

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


示例2: __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


示例3: init_window

    def init_window(self):
        if self.window:
            return
        self.window = Gtk.Window(title="Subplot Configuration Tool")

        try:
            self.window.window.set_icon_from_file(window_icon)
        except Exception:
            # we presumably already logged a message on the
            # failure of the main plot, don't keep reporting
            pass

        self.vbox = Gtk.Box()
        self.vbox.set_property("orientation", Gtk.Orientation.VERTICAL)
        self.window.add(self.vbox)
        self.vbox.show()
        self.window.connect('destroy', self.destroy)

        toolfig = Figure(figsize=(6, 3))
        canvas = self.figure.canvas.__class__(toolfig)

        toolfig.subplots_adjust(top=0.9)
        SubplotTool(self.figure, toolfig)

        w = int(toolfig.bbox.width)
        h = int(toolfig.bbox.height)

        self.window.set_default_size(w, h)

        canvas.show()
        self.vbox.pack_start(canvas, True, True, 0)
        self.window.show()
开发者ID:jklymak,项目名称:matplotlib,代码行数:32,代码来源:backend_gtk3.py


示例4: __init__

    def __init__(self, viewer, selected):
        self.selected = selected
        self.ids = [str(i) + " - " + str(s) for i, s in enumerate(selected)]
        t2 = Tk.Toplevel(viewer)
        t2.title('Data Range Editor')
        t2.transient(viewer)

        # Image selection combobox
        sel_fr = Tk.Frame(master=t2)
        Tk.Label(sel_fr, text="Image:").pack(side=Tk.LEFT)
        self.imagesel = ttk.Combobox(sel_fr)
        self.imagesel['values'] = [str(s) for s in selected]
        self.imagesel.bind('<<ComboboxSelected>>', self.update)

        im = self.selected[0]
        self.imagesel.set(self.ids[0])

        self.imagesel.pack(side=Tk.LEFT)
        sel_fr.pack(side=Tk.TOP)

        # Grid showing current vmin, vmax and original vmin,vmax
        lim_fr = Tk.Frame(master=t2)
        Tk.Label(lim_fr, text="Upper limit:").grid(row=1,column=1)
        Tk.Label(lim_fr, text="Lower limit:").grid(row=2,column=1)

        self.ulim_orig, self.llim_orig = Tk.StringVar(), Tk.StringVar()
        self.ulim, self.llim = Tk.StringVar(), Tk.StringVar()

        self.upper_limit = Tk.Entry(lim_fr, textvariable=self.ulim)
        self.lower_limit = Tk.Entry(lim_fr, textvariable=self.llim)
        self.upper_limit.grid(row=1,column=2)
        self.lower_limit.grid(row=2,column=2)

        upper_limit_orig = Tk.Entry(lim_fr, textvariable=self.ulim_orig, state=Tk.DISABLED)
        lower_limit_orig = Tk.Entry(lim_fr, textvariable=self.llim_orig, state=Tk.DISABLED)
        upper_limit_orig.grid(row=1,column=3)
        lower_limit_orig.grid(row=2,column=3)

        lim_fr.pack(side=Tk.BOTTOM, fill=Tk.NONE, expand=0)

        # Button frame
        buttons = Tk.Frame(master=t2)
        self.all_images = Tk.BooleanVar()
        self.all_images.set(False)
        Tk.Checkbutton(buttons, text="Apply to all images", variable=self.all_images).pack(side=Tk.TOP)
        apply = Tk.Button(master=buttons, text='Apply', command=self.set_limits)
        apply.pack(side=Tk.RIGHT)
        reset = Tk.Button(master=buttons, text='Reset', command=self.reset)
        reset.pack(side=Tk.RIGHT)
        buttons.pack(side=Tk.BOTTOM, fill=Tk.NONE, expand=0)

        # Matplotlib figure
        f = Figure(figsize=(5,4), dpi=100)
        self.a = f.add_subplot(111)
        self.canvas = FigureCanvasTkAgg(f, master=t2)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
        self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

        self.update()
开发者ID:majuvi,项目名称:capgrind,代码行数:60,代码来源:Widgets.py


示例5: WattrGraphPanel

class WattrGraphPanel( WattrGUI.GraphPanel ):

    subplot = 0
    plots = {}

    def __init__(self, parent, fgsize=None, dpi=None):
        super(WattrGraphPanel, self).__init__(parent)
        self.figure = Figure(fgsize, dpi)
        #Transparent figure face color
        self.figure.set_facecolor((0,0,0,0,))
        self.canvas = FigureCanvasWxAgg(self, -1, self.figure)
        # Now put all into a sizer
        sizer = self.GetSizer()
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, wx.LEFT|wx.TOP|wx.GROW)
        # Best to allow the toolbar to resize!
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        sizer.Add(self.toolbar, 0, wx.GROW)
        self.Fit()

    def add_plot(self, x=1, y=1):
        self.subplot += 1
        plot = self.figure.add_subplot(x, y, self.subplot)
        plot.ticklabel_format(axis='y', style='plain', useOffset=False)
        plot.ticklabel_format(axis='x', style='plain', useOffset=False)
        self.plots[self.subplot] = plot
        return plot
    
    def draw(self):
        self.canvas.draw()
开发者ID:bxm156,项目名称:EECS398,代码行数:31,代码来源:WattrGraphPanel.py


示例6: addedRecently

 def addedRecently(self, numdays=30, attr='created'):
     self.calcStats()
     days = {}
     fig = Figure(figsize=(self.width, self.height), dpi=self.dpi)
     limit = self.endOfDay - (numdays) * 86400
     res = self.deck.s.column0("select %s from cards where %s >= %f" %
                               (attr, attr, limit))
     for r in res:
         d = int((r - self.endOfDay) / 86400.0)
         days[d] = days.get(d, 0) + 1
     self.addMissing(days, -numdays+1, 0)
     graph = fig.add_subplot(111)
     intervals = self.unzip(days.items())
     if attr == 'created':
         colour = addedC
     else:
         colour = firstC
     self.varGraph(graph, numdays, colour, *intervals)
     graph.set_xlim(xmin=-numdays+1, xmax=1)
     graph.set_xlabel("Day (0 = today)")
     if attr == 'created':
         graph.set_ylabel("Cards Added")
     else:
         graph.set_ylabel("Cards First Answered")
     return fig
开发者ID:ACEfanatic02,项目名称:anki,代码行数:25,代码来源:graphs.py


示例7: graph_prices

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


示例8: DevPlot

class DevPlot(Plot):

  def __init__(self,k1={'intel_snb' : ['intel_snb','intel_snb','intel_snb']},k2={'intel_snb':['LOAD_1D_ALL','INSTRUCTIONS_RETIRED','LOAD_OPS_ALL']},processes=1,**kwargs):
    self.k1 = k1
    self.k2 = k2
    super(DevPlot,self).__init__(processes=processes,**kwargs)

  def plot(self,jobid,job_data=None):
    self.setup(jobid,job_data=job_data)
    cpu_name = self.ts.pmc_type
    type_name=self.k1[cpu_name][0]
    events = self.k2[cpu_name]

    ts=self.ts

    n_events = len(events)
    self.fig = Figure(figsize=(8,n_events*2+3),dpi=110)

    do_rate = True
    scale = 1.0
    if type_name == 'mem': 
      do_rate = False
      scale=2.0**10
    if type_name == 'cpu':
      scale=ts.wayness*100.0

    for i in range(n_events):
      self.ax = self.fig.add_subplot(n_events,1,i+1)
      self.plot_lines(self.ax, [i], 3600., yscale=scale, do_rate = do_rate)
      self.ax.set_ylabel(events[i],size='small')
    self.ax.set_xlabel("Time (hr)")
    self.fig.subplots_adjust(hspace=0.5)
    #self.fig.tight_layout()

    self.output('devices')
开发者ID:rtevans,项目名称:tacc_stats,代码行数:35,代码来源:devplot.py


示例9: 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


示例10: player_wp

def player_wp(request, code):
    try:
        player = Player.objects.get(code=code)
    except Player.DoesNotExist:
        raise Http404

    points = player.weekly_points.values_list('points', flat=True)
    response = HttpResponse(content_type='image/png')
    
    if points:
        weeks = list(player.weekly_points.values_list('week', flat=True))
        fig = Figure(figsize=(0.4 * min(max(10, weeks[-1]), 22), 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 p, rect in zip(points, rects):
            if p != 0:
                if p < 0:
                    h = p * 2 - 1
                elif p > 0:
                    h = p + 1
                ax.text(rect.get_x() + rect.get_width() / 2., h, str(p),
                        fontsize=10, color='black', ha='center')
        ax.set_xlim((0.5, max(10, weeks[-1]) + 0.5))
    else:
        fig = Figure(figsize=(1, 1), dpi=1, facecolor='white') # return one white pixel

    canvas = FigureCanvas(fig)
    canvas.print_png(response)

    return response
开发者ID:LS80,项目名称:FFL,代码行数:34,代码来源:views.py


示例11: __init__

  def __init__(self):
    c   = 3.0e+11        # speed of light, um/ms
    cs  = 2.8e-11        # cross section, um^2 
    n   = 1.5
    self.WI  = (c/n)*cs       # 18.0,  um^3/ms   
    self.Nv  = 5.0e+7         # 5.0e+7 1/um^3 - density of active particles
    self.W2  = 1./0.23        # 1/ms - 1/spontaneous emission lifetime (2->1 transitions)
    self.W3  = 1.e-3*self.W2  # 1/ms - 1/spontaneous emission lifetime (3->2 transitions)
    self.eta = 1.e-16
    tb, te, self.ts = 0.0, 1.0, 1.0e-4

    self.x  = arange(tb,te,self.ts)
    self.Np = len(self.x)
    self.y1 = ndarray(shape=(self.Np), dtype='float')
    self.y2 = ndarray(shape=(self.Np), dtype='float')
#    self.y3 = ndarray(shape=(self.Np), dtype='float')
    self.y4 = ndarray(shape=(self.Np), dtype='float')

    self.PlotWindow = Tk.Toplevel()
    self.PlotWindow.title('numerical simulation of kinetic equations')
    fig = Figure(figsize=(10,6), dpi=100)
    self.g1 = fig.add_subplot(211)
    self.g2 = fig.add_subplot(212)
    self.canvas = FigureCanvasTkAgg(fig, self.PlotWindow)
    self.canvas.show()
    self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
    self.toolbar = NavigationToolbar2TkAgg( self.canvas, self.PlotWindow)
    self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
开发者ID:muchnoi,项目名称:NdYAG,代码行数:28,代码来源:NdYAG.py


示例12: 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


示例13: TestDialog

class TestDialog( QDialog, Ui_dlgMPLTest ):
    def __init__( self, parent = None ):
        super( TestDialog, self ).__init__( parent )
        self.setupUi( self )
        
        # initialize mpl plot
        self.figure = Figure()
        #self.figure.set_figsize_inches( ( 4.3, 4.2 ) )
        self.axes = self.figure.add_subplot( 111 )
        self.figure.suptitle( "Frequency distribution", fontsize = 12 )
        self.axes.grid( True )
        self.canvas = FigureCanvas( self.figure )
        
        layout = QVBoxLayout()
        self.widgetPlot.setLayout(layout)
        layout.addWidget(self.canvas)
        #self.canvas.setParent( self.widgetPlot )
        
        # draw mpl plot
        #self.axes.clear()
        #self.axes.grid( True )
        #self.figure.suptitle( "Frequency distribution", fontsize = 12 )
        self.axes.set_ylabel( "Count", fontsize = 8 )
        self.axes.set_xlabel( "Values", fontsize = 8 )
        x = [ 4, 1, 5, 3, 3, 2, 3, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1 ]
        n, bins, pathes = self.axes.hist( x, 18, alpha=0.5, histtype = "bar" )
        self.canvas.draw()
        
        self.setWindowTitle( self.tr( "MPL test" ) )
开发者ID:imanmirzaie,项目名称:qttests,代码行数:29,代码来源:tt4.py


示例14: plot_sfh

def plot_sfh(model_sfh, mock_sfh, plot_path):
    labels = {'lewis': r'ACS-MS', 'oir_all': r'OIR-ALL'}
    colors = {'lewis': 'dodgerblue', 'oir_all': 'maroon'}

    fig = Figure(figsize=(3.5, 3.5), frameon=False)
    canvas = FigureCanvas(fig)
    gs = gridspec.GridSpec(1, 1,
                           left=0.18, right=0.95, bottom=0.15, top=0.95,
                           wspace=None, hspace=None,
                           width_ratios=None, height_ratios=None)
    ax = fig.add_subplot(gs[0])
    for plane_key in ['lewis', 'oir_all']:
        if plane_key not in model_sfh['sfh'].keys():
            continue
        plot_single_sfh_line(ax, model_sfh['sfh'][plane_key],
                             label=labels[plane_key],
                             color=colors[plane_key],
                             drawstyle='steps-mid')
        _plot_mean_age(ax, model_sfh['sfh'][plane_key].attrs['mean_age'],
                       c=colors[plane_key])

    # plot_single_sfh_line(ax, model_sfh, label='Model', color='k')
    # print model_sfh['sfr']
    _plot_mock_sfh(ax, mock_sfh, lw=1.5, c='k', label='Mock')
    _plot_mean_age(ax, mock_sfh.attrs['mean_age'])

    ax.legend(loc='lower left', fontsize=8, frameon=True)

    gs.tight_layout(fig, pad=1.08, h_pad=None, w_pad=None, rect=None)
    canvas.print_figure(plot_path + ".pdf", format="pdf")
开发者ID:jonathansick,项目名称:androcmd,代码行数:30,代码来源:plot_mock_sfh.py


示例15: nextDue

    def nextDue(self, days=30):
        self.calcStats()
        fig = Figure(figsize=(self.width, self.height), dpi=self.dpi)
        graph = fig.add_subplot(111)
        dayslists = [self.stats['next'], self.stats['daysByType']['mature']]

        for dayslist in dayslists:
            self.addMissing(dayslist, self.stats['lowestInDay'], days)

        argl = []

        for dayslist in dayslists:
            dl = [x for x in dayslist.items() if x[0] <= days]
            argl.extend(list(self.unzip(dl)))

        self.varGraph(graph, days, [dueYoungC, dueMatureC], *argl)

        cheat = fig.add_subplot(111)
        b1 = cheat.bar(0, 0, color = dueYoungC)
        b2 = cheat.bar(1, 0, color = dueMatureC)

        cheat.legend([b1, b2], [
            "Young",
            "Mature"], loc='upper right')

        graph.set_xlim(xmin=self.stats['lowestInDay'], xmax=days+1)
        graph.set_xlabel("Day (0 = today)")
        graph.set_ylabel("Cards Due")

        return fig
开发者ID:ACEfanatic02,项目名称:anki,代码行数:30,代码来源:graphs.py


示例16: simple

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
    print "hello"
    
    #print form['subject'].value()
    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:dpiscia,项目名称:green_building,代码行数:28,代码来源:views.py


示例17: workDone

    def workDone(self, days=30):
        self.calcStats()

        for type in ["dayRepsNew", "dayRepsYoung", "dayRepsMature"]:
            self.addMissing(self.stats[type], -days, 0)

        fig = Figure(figsize=(self.width, self.height), dpi=self.dpi)
        graph = fig.add_subplot(111)

        args = sum((self.unzip(self.stats[type].items(), limit=days, reverseLimit=True) for type in ["dayRepsMature", "dayRepsYoung", "dayRepsNew"][::-1]), [])

        self.varGraph(graph, days, [reviewNewC, reviewYoungC, reviewMatureC], *args)

        cheat = fig.add_subplot(111)
        b1 = cheat.bar(-3, 0, color = reviewNewC)
        b2 = cheat.bar(-4, 0, color = reviewYoungC)
        b3 = cheat.bar(-5, 0, color = reviewMatureC)

        cheat.legend([b1, b2, b3], [
            "New",
            "Young",
            "Mature"], loc='upper left')

        graph.set_xlim(xmin=-days+1, xmax=1)
        graph.set_ylim(ymax=max(max(a for a in args[1::2])) + 10)
        graph.set_xlabel("Day (0 = today)")
        graph.set_ylabel("Cards Answered")

        return fig
开发者ID:ACEfanatic02,项目名称:anki,代码行数:29,代码来源:graphs.py


示例18: _test_determinism_save

def _test_determinism_save(filename, usetex):
    # This function is mostly copy&paste from "def test_visibility"
    # To require no GUI, we use Figure and FigureCanvasSVG
    # instead of plt.figure and fig.savefig
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_svg import FigureCanvasSVG
    from matplotlib import rc
    rc('svg', hashsalt='asdf')
    rc('text', usetex=usetex)

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

    x = np.linspace(0, 4 * np.pi, 50)
    y = np.sin(x)
    yerr = np.ones_like(y)

    a, b, c = ax.errorbar(x, y, yerr=yerr, fmt='ko')
    for artist in b:
        artist.set_visible(False)
    ax.set_title('A string $1+2+\\sigma$')
    ax.set_xlabel('A string $1+2+\\sigma$')
    ax.set_ylabel('A string $1+2+\\sigma$')

    FigureCanvasSVG(fig).print_svg(filename)
开发者ID:vapier,项目名称:matplotlib,代码行数:25,代码来源:test_backend_svg.py


示例19: 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


示例20: imsave

def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, origin=None):
    """
    Saves a 2D :class:`numpy.array` as an image with one pixel per element.
    The output formats available depend on the backend being used.

    Arguments:
      *fname*:
        A string containing a path to a filename, or a Python file-like object.
        If *format* is *None* and *fname* is a string, the output
        format is deduced from the extension of the filename.
      *arr*:
        A 2D array.
    Keyword arguments:
      *vmin*/*vmax*: [ None | scalar ]
        *vmin* and *vmax* set the color scaling for the image by fixing the
        values that map to the colormap color limits. If either *vmin* or *vmax*
        is None, that limit is determined from the *arr* min/max value.
      *cmap*:
        cmap is a colors.Colormap instance, eg cm.jet.
        If None, default to the rc image.cmap value.
      *format*:
        One of the file extensions supported by the active
        backend.  Most backends support png, pdf, ps, eps and svg.
      *origin*
        [ 'upper' | 'lower' ] Indicates where the [0,0] index of
        the array is in the upper left or lower left corner of
        the axes. Defaults to the rc image.origin value.
    """
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure

    fig = Figure(figsize=arr.shape[::-1], dpi=1, frameon=False)
    canvas = FigureCanvas(fig)
    fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin)
    fig.savefig(fname, dpi=1, format=format)
开发者ID:zoccolan,项目名称:eyetracker,代码行数:35,代码来源:image.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python finance.candlestick函数代码示例发布时间:2022-05-27
下一篇:
Python moves.zip函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap