Python matplotlib.figure() Examples

The following are 30 code examples for showing how to use matplotlib.figure(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module matplotlib , or try the search function .

Example 1
Project: RF-Monitor   Author: EarToEarOak   File: dialog_spectrum.py    License: 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 2
Project: RF-Monitor   Author: EarToEarOak   File: dialog_timeline.py    License: 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 3
Project: skan   Author: jni   File: gui.py    License: 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 4
Project: ocelot   Author: ocelot-collab   File: accelerator.py    License: 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 5
Project: ocelot   Author: ocelot-collab   File: accelerator.py    License: 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 6
Project: Computable   Author: ktraunmueller   File: gridspec.py    License: 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 7
Project: Computable   Author: ktraunmueller   File: gridspec.py    License: 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 8
Project: Computable   Author: ktraunmueller   File: backend_tkagg.py    License: 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 9
Project: Computable   Author: ktraunmueller   File: backend_tkagg.py    License: 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 10
Project: Computable   Author: ktraunmueller   File: backend_webagg.py    License: 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 11
Project: Computable   Author: ktraunmueller   File: backend_gtk.py    License: 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 12
Project: Computable   Author: ktraunmueller   File: backend_gtk.py    License: 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 13
Project: Computable   Author: ktraunmueller   File: backend_pdf.py    License: 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 14
Project: garden.matplotlib   Author: kivy-garden   File: test_backend.py    License: MIT License 5 votes vote down vote up
def figure_enter(event):
    print('figure enter mpl') 
Example 15
Project: garden.matplotlib   Author: kivy-garden   File: test_backend.py    License: MIT License 5 votes vote down vote up
def figure_leave(event):
    print('figure leaving mpl') 
Example 16
Project: garden.matplotlib   Author: kivy-garden   File: test_backend.py    License: MIT License 5 votes vote down vote up
def close(event):
    print('closing figure') 
Example 17
Project: garden.matplotlib   Author: kivy-garden   File: backend_kivyagg.py    License: 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 18
Project: garden.matplotlib   Author: kivy-garden   File: backend_kivyagg.py    License: 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 19
Project: garden.matplotlib   Author: kivy-garden   File: backend_kivyagg.py    License: MIT License 5 votes vote down vote up
def mainloop(self):
        global my_canvas
        global toolbar
        app = App.get_running_app()
        if app is None:
            app = MPLKivyApp(figure=my_canvas, toolbar=toolbar)
            app.run() 
Example 20
Project: garden.matplotlib   Author: kivy-garden   File: backend_kivyagg.py    License: MIT License 5 votes vote down vote up
def __init__(self, figure, **kwargs):
        self.figure = figure
        self.bind(size=self._on_size_changed)
        super(FigureCanvasKivyAgg, self).__init__(figure=self.figure, **kwargs)
        self.img_texture = None
        self.img_rect = None
        self.blit() 
Example 21
Project: garden.matplotlib   Author: kivy-garden   File: backend_kivyagg.py    License: MIT License 5 votes vote down vote up
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()
        color = self.figure.get_facecolor()
        with self.canvas:
            Color(*color)
            Rectangle(pos=self.pos, size=(w, h))
            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 
Example 22
Project: garden.matplotlib   Author: kivy-garden   File: backend_kivyagg.py    License: MIT License 5 votes vote down vote up
def _print_image(self, filename, *args, **kwargs):
        '''Write out format png. The image is saved with the filename given.
        '''
        l, b, w, h = self.figure.bbox.bounds
        img = None
        if self.img_texture is None:
            texture = Texture.create(size=(w, h))
            texture.blit_buffer(bytes(self.get_renderer().buffer_rgba()),
                                colorfmt='rgba', bufferfmt='ubyte')
            texture.flip_vertical()
            img = Image(texture)
        else:
            img = Image(self.img_texture)
        img.save(filename) 
Example 23
Project: garden.matplotlib   Author: kivy-garden   File: backend_kivy.py    License: MIT License 5 votes vote down vote up
def build(self):
        EventLoop.ensure_window()
        layout = FloatLayout()
        if self.figure:
            self.figure.size_hint_y = 0.9
            layout.add_widget(self.figure)
        if self.toolbar:
            self.toolbar.size_hint_y = 0.1
            layout.add_widget(self.toolbar)
        return layout 
Example 24
Project: garden.matplotlib   Author: kivy-garden   File: backend_kivy.py    License: 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 25
Project: garden.matplotlib   Author: kivy-garden   File: backend_kivy.py    License: 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 = FigureCanvasKivy(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
Project: garden.matplotlib   Author: kivy-garden   File: backend_kivy.py    License: MIT License 5 votes vote down vote up
def __init__(self, widget):
        super(RendererKivy, self).__init__()
        self.widget = widget
        self.dpi = widget.figure.dpi
        self._markers = {}
        #  Can be enhanced by using TextToPath matplotlib, textpath.py
        self.mathtext_parser = MathTextParser("Bitmap")
        self.list_goraud_triangles = []
        self.clip_rectangles = []
        self.labels_inside_plot = [] 
Example 27
Project: garden.matplotlib   Author: kivy-garden   File: backend_kivy.py    License: MIT License 5 votes vote down vote up
def __init__(self, figure, **kwargs):
        Window.bind(mouse_pos=self._on_mouse_pos)
        self.bind(size=self._on_size_changed)
        self.bind(pos=self._on_pos_changed)
        self.entered_figure = True
        self.figure = figure
        super(FigureCanvasKivy, self).__init__(figure=self.figure, **kwargs) 
Example 28
Project: garden.matplotlib   Author: kivy-garden   File: backend_kivy.py    License: MIT License 5 votes vote down vote up
def _on_size_changed(self, *args):
        '''Changes the size of the matplotlib figure based on the size of the
           widget. The widget will change size according to the parent Layout
           size.
        '''
        w, h = self.size
        dpival = self.figure.dpi
        winch = float(w) / dpival
        hinch = float(h) / dpival
        self.figure.set_size_inches(winch, hinch, forward=False)
        self.resize_event()
        self.draw() 
Example 29
Project: garden.matplotlib   Author: kivy-garden   File: backend_kivy.py    License: MIT License 5 votes vote down vote up
def print_png(self, filename, *args, **kwargs):
        '''Call the widget function to make a png of the widget.
        '''
        fig = FigureCanvasAgg(self.figure)
        FigureCanvasAgg.draw(fig)

        l, b, w, h = self.figure.bbox.bounds
        texture = Texture.create(size=(w, h))
        texture.blit_buffer(bytes(fig.get_renderer().buffer_rgba()),
                                colorfmt='rgba', bufferfmt='ubyte')
        texture.flip_vertical()
        img = Image(texture)
        img.save(filename) 
Example 30
Project: ocelot   Author: ocelot-collab   File: accelerator.py    License: GNU General Public License v3.0 5 votes vote down vote up
def plot_API(lat, legend=True, fig_name=1, grid=True, font_size=12, excld_legend=None):
    """
    Function creates a picture with lattice on the bottom part of the picture and top part of the picture can be
    plot arbitrary lines.

    :param lat: MagneticLattice
    :param legend: True, description of the elements, if False it is switched legend off
    :return: fig, ax
    """
    fig = plt.figure(fig_name)
    plt.rc('axes', grid=grid)
    plt.rc('grid', color='0.75', linestyle='-', linewidth=0.5)
    left, width = 0.1, 0.85
    rect2 = [left, 0.19, width, 0.69]
    rect3 = [left, 0.07, width, 0.12]


    #rect1 = [left, 0.65, width, 0.3]
    #rect2 = [left, 0.19, width, 0.46]
    #rect3 = [left, 0.07, width, 0.12]

    ax_xy = fig.add_axes(rect2)  #left, bottom, width, height
    ax_el = fig.add_axes(rect3, sharex=ax_xy)


    for ax in ax_xy, ax_el:
        if ax!=ax_el:
            for label in ax.get_xticklabels():
                label.set_visible(False)

    ax_xy.grid(grid)
    ax_el.set_yticks([])
    ax_el.grid(grid)

    ax_xy.tick_params(axis='both', labelsize=font_size)

    fig.subplots_adjust(hspace=0)

    plot_elems(fig, ax_el, lat, legend=legend, y_scale=0.8, font_size=font_size, excld_legend=excld_legend)

    return fig, ax_xy