Python matplotlib.figure() Examples

The following are 30 code examples of matplotlib.figure(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib , or try the search function .
Example #1
Source File: backend_pdf.py    From Computable with MIT License 6 votes vote down vote up
def print_pdf(self, filename, **kwargs):
        image_dpi = kwargs.get('dpi', 72) # dpi to use for images
        self.figure.set_dpi(72)           # there are 72 pdf points to an inch
        width, height = self.figure.get_size_inches()
        if isinstance(filename, PdfPages):
            file = filename._file
        else:
            file = PdfFile(filename)
        try:
            file.newPage(width, height)
            _bbox_inches_restore = kwargs.pop("bbox_inches_restore", None)
            renderer = MixedModeRenderer(self.figure,
                                         width, height, image_dpi, RendererPdf(file, image_dpi),
                                         bbox_inches_restore=_bbox_inches_restore)
            self.figure.draw(renderer)
            renderer.finalize()
        finally:
            if isinstance(filename, PdfPages): # finish off this page
                file.endStream()
            else:            # we opened the file above; now finish it off
                file.close() 
Example #2
Source File: dialog_spectrum.py    From RF-Monitor with GNU General Public License v2.0 6 votes vote down vote up
def __setup_plot(self):
        figure = Figure(facecolor='lightgrey')

        self._axes = figure.add_subplot(111)
        self._axes.set_title('Spectrum')
        self._axes.set_xlabel('Frequency (MHz)')
        self._axes.set_ylabel('Level (dB)')
        self._axes.autoscale_view(True, True, True)
        self._axes.grid(True)

        self._spectrum, = self._axes.plot([], [], 'b-', label='Spectrum')

        self._canvas = FigureCanvas(self._panelPlot, -1, figure)
        self._canvas.mpl_connect('motion_notify_event', self.__on_motion)

        Legend.__init__(self, self._axes, self._canvas) 
Example #3
Source File: dialog_timeline.py    From RF-Monitor with GNU General Public License v2.0 6 votes vote down vote up
def __setup_plot(self):
        figure = Figure(facecolor='lightgrey')

        self._axes = figure.add_subplot(111)
        self._axes.set_title('Timeline')
        self._axes.set_xlabel('Time')
        self._axes.set_ylabel('Frequency (MHz)')
        self._axes.grid(True)

        locator = AutoDateLocator()
        formatter = AutoDateFormatter(locator)
        self._axes.xaxis.set_major_formatter(formatter)
        self._axes.xaxis.set_major_locator(locator)
        formatter = ScalarFormatter(useOffset=False)
        self._axes.yaxis.set_major_formatter(formatter)
        self._axes.yaxis.set_minor_locator(AutoMinorLocator(10))

        self._canvas = FigureCanvas(self._panelPlot, -1, figure)
        self._canvas.mpl_connect('motion_notify_event', self.__on_motion)

        Legend.__init__(self, self._axes, self._canvas) 
Example #4
Source File: gui.py    From skan with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def make_figure_window(self):
        self.figure_window = tk.Toplevel(self)
        self.figure_window.wm_title('Preview')
        screen_dpi = self.figure_window.winfo_fpixels('1i')
        screen_width = self.figure_window.winfo_screenwidth()  # in pixels
        figure_width = screen_width / 2 / screen_dpi
        figure_height = 0.75 * figure_width
        self.figure = Figure(figsize=(figure_width, figure_height),
                             dpi=screen_dpi)
        ax0 = self.figure.add_subplot(221)
        axes = [self.figure.add_subplot(220 + i, sharex=ax0, sharey=ax0)
                for i in range(2, 5)]
        self.axes = np.array([ax0] + axes)
        canvas = FigureCanvasTkAgg(self.figure, master=self.figure_window)
        canvas.show()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        toolbar = NavigationToolbar2Tk(canvas, self.figure_window)
        toolbar.update()
        canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) 
Example #5
Source File: accelerator.py    From ocelot with GNU General Public License v3.0 6 votes vote down vote up
def show_da(out_da, x_array, y_array, title=""):
    nx = len(x_array)
    ny = len(y_array)
    out_da = out_da.reshape(ny,nx)
    xmin, xmax, ymin, ymax = np.min(x_array), np.max(x_array), np.min(y_array), np.max(y_array)
    extent = xmin, xmax, ymin, ymax

    plt.figure(figsize=(10, 7))
    fig1 = plt.contour(out_da, linewidths=2,extent = extent)#, colors = 'r')

    plt.grid(True)
    plt.title(title)
    plt.xlabel("X, m")
    plt.ylabel("Y, m")
    cb = plt.colorbar()
    cb.set_label('Nturns')

    plt.show() 
Example #6
Source File: accelerator.py    From ocelot with GNU General Public License v3.0 6 votes vote down vote up
def apply(self,  p_array, dz):
        nbins_x = 400
        nbins_y = 400
        interpolation = "bilinear"
        fig = plt.figure( figsize=None)
        ax_xs = plt.subplot(211)

        show_density(p_array.tau() * 1e3, p_array.x() * 1e3, ax=ax_xs, nbins_x=nbins_x, nbins_y=nbins_y,
                     interpolation=interpolation, ylabel='x [mm]',
                     title="Top view", grid=True, show_xtick_label=False, limits=[[0.025, 0.075], [-2, 2]])
        ax_ys = plt.subplot(212, sharex=ax_xs)

        show_density(p_array.tau() * 1e3, p_array.y() * 1e3, ax=ax_ys, nbins_x=nbins_x, nbins_y=nbins_y,
                     interpolation=interpolation, xlabel="s, [mm]", ylabel='y [mm]', nfig=50,
                     title="Side view", figsize=None, grid=True, show_xtick_label=True,limits=[[0.025, 0.075], [-2, 2]])

        dig = str(self.napply)      
        name = "0"*(4 - len(dig)) + dig

        plt.savefig(name)
        self.napply += 1
        plt.clf() 
Example #7
Source File: gridspec.py    From Computable with MIT License 6 votes vote down vote up
def __init__(self, nrows, ncols,
                 left=None, bottom=None, right=None, top=None,
                 wspace=None, hspace=None,
                 width_ratios=None, height_ratios=None):
        """
        The number of rows and number of columns of the
        grid need to be set. Optionally, the subplot layout parameters
        (e.g., left, right, etc.) can be tuned.
        """
        #self.figure = figure
        self.left=left
        self.bottom=bottom
        self.right=right
        self.top=top
        self.wspace=wspace
        self.hspace=hspace

        GridSpecBase.__init__(self, nrows, ncols,
                              width_ratios=width_ratios,
                              height_ratios=height_ratios)
        #self.set_width_ratios(width_ratios)
        #self.set_height_ratios(height_ratios) 
Example #8
Source File: gridspec.py    From Computable with MIT License 6 votes vote down vote up
def get_subplot_params(self, fig=None):
        """
        return a dictionary of subplot layout parameters. The default
        parameters are from rcParams unless a figure attribute is set.
        """
        from matplotlib.figure import SubplotParams
        import copy
        if fig is None:
            kw = dict([(k, rcParams["figure.subplot."+k]) \
                       for k in self._AllowedKeys])
            subplotpars = SubplotParams(**kw)
        else:
            subplotpars = copy.copy(fig.subplotpars)

        update_kw = dict([(k, getattr(self, k)) for k in self._AllowedKeys])
        subplotpars.update(**update_kw)

        return subplotpars 
Example #9
Source File: backend_tkagg.py    From Computable with MIT License 6 votes vote down vote up
def save_figure(self, *args):
        fs = FileDialog.SaveFileDialog(master=self.window,
                                       title='Save the figure')
        try:
            self.lastDir
        except AttributeError:
            self.lastDir = os.curdir

        fname = fs.go(dir_or_file=self.lastDir) # , pattern="*.png")
        if fname is None: # Cancel
            return

        self.lastDir = os.path.dirname(fname)
        try:
            self.canvas.print_figure(fname)
        except IOError as msg:
            err = '\n'.join(map(str, msg))
            msg = 'Failed to save %s: Error msg was\n\n%s' % (
                fname, err)
            error_msg_tkpaint(msg) 
Example #10
Source File: backend_tkagg.py    From Computable with MIT License 6 votes vote down vote up
def _init_toolbar(self):
        xmin, xmax = self.canvas.figure.bbox.intervalx
        height, width = 50, xmax-xmin
        Tk.Frame.__init__(self, master=self.window,
                          width=int(width), height=int(height),
                          borderwidth=2)

        self.update()  # Make axes menu

        for text, tooltip_text, image_file, callback in self.toolitems:
            if text is None:
                # spacer, unhandled in Tk
                pass
            else:
                button = self._Button(text=text, file=image_file,
                                   command=getattr(self, callback))
                if tooltip_text is not None:
                    ToolTip.createToolTip(button, tooltip_text)

        self.message = Tk.StringVar(master=self)
        self._message_label = Tk.Label(master=self, textvariable=self.message)
        self._message_label.pack(side=Tk.RIGHT)
        self.pack(side=Tk.BOTTOM, fill=Tk.X) 
Example #11
Source File: backend_webagg.py    From Computable with MIT License 6 votes vote down vote up
def get_renderer(self, cleared=False):
        # Mirrors super.get_renderer, but caches the old one
        # so that we can do things such as prodce a diff image
        # in get_diff_image
        _, _, w, h = self.figure.bbox.bounds
        key = w, h, self.figure.dpi
        try:
            self._lastKey, self._renderer
        except AttributeError:
            need_new_renderer = True
        else:
            need_new_renderer = (self._lastKey != key)

        if need_new_renderer:
            self._renderer = backend_agg.RendererAgg(
                w, h, self.figure.dpi)
            self._last_renderer = backend_agg.RendererAgg(
                w, h, self.figure.dpi)
            self._lastKey = key

        return self._renderer 
Example #12
Source File: backend_gtk.py    From Computable with MIT License 6 votes vote down vote up
def __init__(self, canvas, window):
        """
        figManager is the FigureManagerGTK instance that contains the
        toolbar, with attributes figure, window and drawingArea

        """
        gtk.Toolbar.__init__(self)

        self.canvas = canvas
        # Note: gtk.Toolbar already has a 'window' attribute
        self.win    = window

        self.set_style(gtk.TOOLBAR_ICONS)

        self._create_toolitems_2_4()
        self.update = self._update_2_4
        self.fileselect = FileChooserDialog(
            title='Save the figure',
            parent=self.win,
            filetypes=self.canvas.get_supported_filetypes(),
            default_filetype=self.canvas.get_default_filetype())
        self.show_all()
        self.update() 
Example #13
Source File: backend_gtk.py    From Computable with MIT License 6 votes vote down vote up
def _update(self):
        'update the active line props from the widgets'
        if not self._inited or not self._updateson: return
        line = self.get_active_line()
        ls = self.get_active_linestyle()
        marker = self.get_active_marker()
        line.set_linestyle(ls)
        line.set_marker(marker)

        button = self.wtree.get_widget('colorbutton_linestyle')
        color = button.get_color()
        r, g, b = [val/65535. for val in (color.red, color.green, color.blue)]
        line.set_color((r,g,b))

        button = self.wtree.get_widget('colorbutton_markerface')
        color = button.get_color()
        r, g, b = [val/65535. for val in (color.red, color.green, color.blue)]
        line.set_markerfacecolor((r,g,b))

        line.figure.canvas.draw() 
Example #14
Source File: test_backend.py    From garden.matplotlib with MIT License 5 votes vote down vote up
def figure_leave(event):
    print('figure leaving mpl') 
Example #15
Source File: backend_webagg.py    From Computable with MIT License 5 votes vote down vote up
def open(self, fignum):
            self.fignum = int(fignum)
            manager = Gcf.get_fig_manager(self.fignum)
            manager.add_web_socket(self)
            _, _, w, h = manager.canvas.figure.bbox.bounds
            manager.resize(w, h)
            self.on_message('{"type":"refresh"}')
            if hasattr(self, 'set_nodelay'):
                self.set_nodelay(True) 
Example #16
Source File: test_backend.py    From garden.matplotlib with MIT License 5 votes vote down vote up
def close(event):
    print('closing figure') 
Example #17
Source File: backend_webagg.py    From Computable with MIT License 5 votes vote down vote up
def draw(self):
        # TODO: Do we just queue the drawing here?  That's what Gtk does
        renderer = self.get_renderer()

        self._png_is_old = True

        backend_agg.RendererAgg.lock.acquire()
        try:
            self.figure.draw(renderer)
        finally:
            backend_agg.RendererAgg.lock.release()
            # Swap the frames
            self.manager.refresh_all() 
Example #18
Source File: backend_webagg.py    From Computable with MIT License 5 votes vote down vote up
def new_figure_manager_given_figure(num, figure):
    """
    Create a new figure manager instance for the given figure.
    """
    canvas = FigureCanvasWebAgg(figure)
    manager = FigureManagerWebAgg(canvas, num)
    return manager 
Example #19
Source File: backend_webagg.py    From Computable with MIT License 5 votes vote down vote up
def new_figure_manager(num, *args, **kwargs):
    """
    Create a new figure manager instance
    """
    FigureClass = kwargs.pop('FigureClass', Figure)
    thisFig = FigureClass(*args, **kwargs)
    return new_figure_manager_given_figure(num, thisFig) 
Example #20
Source File: backend_webagg.py    From Computable with MIT License 5 votes vote down vote up
def mainloop(self):
        WebAggApplication.initialize()

        url = "http://127.0.0.1:{port}{prefix}".format(
                port=WebAggApplication.port,
                prefix=WebAggApplication.url_prefix)

        if rcParams['webagg.open_in_browser']:
            import webbrowser
            webbrowser.open(url)
        else:
            print("To view figure, visit {0}".format(url))

        WebAggApplication.start() 
Example #21
Source File: backend_tkagg.py    From Computable with MIT License 5 votes vote down vote up
def update(self):
        _focus = windowing.FocusManager()
        self._axes = self.canvas.figure.axes
        naxes = len(self._axes)
        #if not hasattr(self, "omenu"):
        #    self.set_active(range(naxes))
        #    self.omenu = AxisMenu(master=self, naxes=naxes)
        #else:
        #    self.omenu.adjust(naxes)
        NavigationToolbar2.update(self) 
Example #22
Source File: backend_kivyagg.py    From garden.matplotlib with MIT License 5 votes vote down vote up
def new_figure_manager(num, *args, **kwargs):
    '''Create a new figure manager instance for the figure given.
    '''
    # if a main-level app must be created, this (and
    # new_figure_manager_given_figure) is the usual place to
    # do it -- see backend_wx, backend_wxagg and backend_tkagg for
    # examples. Not all GUIs require explicit instantiation of a
    # main-level app (egg backend_gtk, backend_gtkagg) for pylab
    FigureClass = kwargs.pop('FigureClass', Figure)
    thisFig = FigureClass(*args, **kwargs)
    return new_figure_manager_given_figure(num, thisFig) 
Example #23
Source File: backend_tkagg.py    From Computable with MIT License 5 votes vote down vote up
def draw_rubberband(self, event, x0, y0, x1, y1):
        height = self.canvas.figure.bbox.height
        y0 =  height-y0
        y1 =  height-y1
        try: self.lastrect
        except AttributeError: pass
        else: self.canvas._tkcanvas.delete(self.lastrect)
        self.lastrect = self.canvas._tkcanvas.create_rectangle(x0, y0, x1, y1)

        #self.canvas.draw() 
Example #24
Source File: backend_tkagg.py    From Computable with MIT License 5 votes vote down vote up
def update(self):
        _focus = windowing.FocusManager()
        self._axes = self.canvas.figure.axes
        naxes = len(self._axes)
        if not hasattr(self, "omenu"):
            self.set_active(range(naxes))
            self.omenu = AxisMenu(master=self, naxes=naxes)
        else:
            self.omenu.adjust(naxes) 
Example #25
Source File: backend_kivyagg.py    From garden.matplotlib with MIT License 5 votes vote down vote up
def new_figure_manager_given_figure(num, figure):
    '''Create a new figure manager instance and a new figure canvas instance
       for the given figure.
    '''
    canvas = FigureCanvasKivyAgg(figure)
    manager = FigureManagerKivy(canvas, num)
    global my_canvas
    global toolbar
    toolbar = manager.toolbar.actionbar if manager.toolbar else None
    my_canvas = canvas
    return manager 
Example #26
Source File: backend_tkagg.py    From Computable with MIT License 5 votes vote down vote up
def scroll_event_windows(self, event):
        """MouseWheel event processor"""
        # need to find the window that contains the mouse
        w = event.widget.winfo_containing(event.x_root, event.y_root)
        if w == self._tkcanvas:
            x = event.x_root - w.winfo_rootx()
            y = event.y_root - w.winfo_rooty()
            y = self.figure.bbox.height - y
            step = event.delta/120.
            FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=event) 
Example #27
Source File: backend_tkagg.py    From Computable with MIT License 5 votes vote down vote up
def scroll_event(self, event):
        x = event.x
        y = self.figure.bbox.height - event.y
        num = getattr(event, 'num', None)
        if   num==4: step = +1
        elif num==5: step = -1
        else:        step =  0

        FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=event) 
Example #28
Source File: backend_kivy.py    From garden.matplotlib with MIT License 5 votes vote down vote up
def new_figure_manager(num, *args, **kwargs):
    '''Create a new figure manager instance for the figure given.
    '''
    # if a main-level app must be created, this (and
    # new_figure_manager_given_figure) is the usual place to
    # do it -- see backend_wx, backend_wxagg and backend_tkagg for
    # examples. Not all GUIs require explicit instantiation of a
    # main-level app (egg backend_gtk, backend_gtkagg) for pylab
    FigureClass = kwargs.pop('FigureClass', Figure)
    thisFig = FigureClass(*args, **kwargs)
    return new_figure_manager_given_figure(num, thisFig) 
Example #29
Source File: backend_tkagg.py    From Computable with MIT License 5 votes vote down vote up
def button_release_event(self, event):
        x = event.x
        # flipy so y=0 is bottom of canvas
        y = self.figure.bbox.height - event.y

        num = getattr(event, 'num', None)

        if sys.platform=='darwin':
            # 2 and 3 were reversed on the OSX platform I
            # tested under tkagg
            if   num==2: num=3
            elif num==3: num=2

        FigureCanvasBase.button_release_event(self, x, y, num, guiEvent=event) 
Example #30
Source File: backend_tkagg.py    From Computable with MIT License 5 votes vote down vote up
def button_press_event(self, event, dblclick=False):
        x = event.x
        # flipy so y=0 is bottom of canvas
        y = self.figure.bbox.height - event.y
        num = getattr(event, 'num', None)

        if sys.platform=='darwin':
            # 2 and 3 were reversed on the OSX platform I
            # tested under tkagg
            if   num==2: num=3
            elif num==3: num=2

        FigureCanvasBase.button_press_event(self, x, y, num, dblclick=dblclick, guiEvent=event)