pyMez.Code.FrontEnds.MatplotlibWxPanel API documentation
Description: An example of how to use wx or wxagg in an application with a custom toolbar, Modified to work insid...

Top

# pyMez.Code.FrontEnds.MatplotlibWxPanel module

An example of how to use wx or wxagg in an application with a custom toolbar, Modified to work inside of BOA by AWS. Serves as an advanced plot window for pyMez. The custom tool bar is MyNavigationToolBar

## Help

`pyMez.Code.FrontEnds`

Documentation Home | API Documentation Home | Examples Home | Index

Show source ≡

    #-----------------------------------------------------------------------------
    # Name:        MatplotlibWxPanel.py
    # Purpose:     To be a plugin advanced plot panel for pyMez
    # Author:      Aric Sanders
    # Created:     3/02/2016
    # License:     MIT License
    #-----------------------------------------------------------------------------
    """
    An example of how to use wx or wxagg in an application with a custom
    toolbar, Modified to work inside of BOA by AWS. Serves as an advanced plot window for pyMez.
    The custom tool bar is MyNavigationToolBar

    Help
    ---------------
    <a href="./index.html">`pyMez.Code.FrontEnds`</a>
    <div>
    <a href="../../../pyMez_Documentation.html">Documentation Home</a> |
    <a href="../../index.html">API Documentation Home</a> |
    <a href="../../../Examples/html/Examples_Home.html">Examples Home</a> |
    <a href="../../../Reference_Index.html">Index</a>
    </div>
    """

    #-------------------------------------------------------------------------------
    # Standard Imports
    import wx
    import os
    import sys

    #-------------------------------------------------------------------------------
    # Third Party imports
    # Used to guarantee to use at least Wx2.8 Was removed.
    sys.path.append(os.path.join(os.path.dirname( __file__ ), '..','..'))

    try:
        from numpy import arange, sin, pi

        import matplotlib
        import matplotlib.ticker as ticker
        matplotlib.use('WXAgg')
        from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
        from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg

        from matplotlib.backends.backend_wx import _load_bitmap
        from matplotlib.figure import Figure
        from numpy.random import rand
        import numpy as np

    except:
        print("Please make sure matplotlib package is installed and in sys.path")
    try:
        from Code.DataHandlers.XMLModels import DataTable
    except:
        print("import of pyMez.Code.DataHandlers.XMLModels failed")

    #-------------------------------------------------------------------------------
    # Constants
    TESTS_DIRECTORY=os.path.join(os.path.dirname(os.path.realpath(__file__)),'Tests')

    #-------------------------------------------------------------------------------
    # Class Definitions

    # This class was ripped from an example on the matplotlib site
    class MyNavigationToolbar(NavigationToolbar2WxAgg):
        """
        Extend the default wx toolbar with your own event handlers
        """
        ON_CUSTOM = wx.NewId()
        def __init__(self, canvas, cankill):
            NavigationToolbar2WxAgg.__init__(self, canvas)

            # for simplicity I'm going to reuse a bitmap from wx, you'll
            # probably want to add your own.wx.ART_FOLDER_OPEN
            #wx.ArtProvider.GetBitmap(wx.ART_FOLDER_OPEN) is the stock icons command
            self.AddSimpleTool(self.ON_CUSTOM, wx.ArtProvider.GetBitmap(wx.ART_FOLDER_OPEN),
                               'Plot measurement', 'Plot an XML data file')
            wx.EVT_TOOL(self, self.ON_CUSTOM, self._on_custom)

            # self.AddSimpleTool(self.ON_CUSTOM, wx.ArtProvider.GetBitmap(wx.ART_FOLDER_OPEN),
            #                    'Click me', 'Activate custom contol')
            #wx.EVT_TOOL(self, self.ON_CUSTOM, self._on_custom)

        def _on_custom(self, evt):
            # add some text to the axes in a random location in axes (0,1)
            # coords) with a random color

    ##        # get the axes
    ##        ax = self.canvas.figure.axes[0]
    ##
    ##        # generate a random location can color
    ##        x,y = tuple(rand(2))
    ##        rgb = tuple(rand(3))
    ##
    ##        # add the text and draw
    ##        ax.text(x, y, 'You clicked me',
    ##                transform=ax.transAxes,
    ##                color=rgb)
    ##        self.canvas.draw()
            # This is a stub out for a file chooser to plot.
            dlg = wx.FileDialog(self, 'Choose a file', TESTS_DIRECTORY, '', '*.*', wx.OPEN)
            try:
                if dlg.ShowModal() == wx.ID_OK:
                    filename = dlg.GetPath()
                    try:
                        data_sheet=DataTable(filename)
                        self.canvas.figure.clear()
                        self.axes = self.canvas.figure.add_subplot(111)
                        ax = self.canvas.figure.axes[0]
                        # This needs to be generalized with a chooser so that things with
                        # lots of columns can be plotted
                        #print(data_sheet.get_attribute_names())

                        if 'Current' in data_sheet.get_attribute_names():
                            y_name='Current'
                        if 'Voltage' in data_sheet.get_attribute_names():
                            x_name='Voltage'

                        else:
                            y_name=data_sheet.get_attribute_names()[0]
                            x_name=data_sheet.get_attribute_names()[1]
                        params={'axes.labelsize': 18,"font.size":18,
                        'legend.fontsize': 18,
                        'xtick.labelsize': 18,
                        'ytick.labelsize': 18,
                        }

                        matplotlib.rcParams.update(params)
                        self.axes.xaxis.set_major_formatter(ticker.ScalarFormatter(useOffset=True))
                        self.axes.yaxis.set_major_formatter(ticker.ScalarFormatter(useOffset=True))
                        #print(x_name,y_name)
                        self.axes.set_xlabel(x_name,fontsize=20)
                        self.axes.set_ylabel(y_name,fontsize=20)
                        x_data=np.array([float(x) for x in data_sheet.to_list(x_name)])
                        y_data=np.array([float(x) for x in data_sheet.to_list(y_name)])
                        ax.plot(x_data,y_data)
                        self.canvas.draw()
                        # Set the Title
                        try:
                            self.Parent.Parent.SetTitle(data_sheet.path)
                        except:
                            pass
                        self.Update()
                    except:
                        raise

            finally:
                dlg.Destroy()
            evt.Skip()

    # In the original example this was a frame, I have modified it to work with BOA
    class MatplotlibWxPanel(wx.Panel):
        """ This is a wx.Panel that shows a plot with a custom toolbar"""
        def __init__(self, parent, id, pos, size, style, name):
            wx.Panel.__init__(self, parent, id, pos, size, style, name)

            self.SetBackgroundColour(wx.NamedColour("WHITE"))

            self.figure = Figure(figsize=(5,4), dpi=100)
            self.axes = self.figure.add_subplot(111)
            t = arange(0.0,3.0,0.01)
            s = sin(2*pi*t)

            self.axes.plot(t,s)

            self.canvas = FigureCanvas(self, -1, self.figure)

            self.sizer = wx.BoxSizer(wx.VERTICAL)
            self.sizer.Add(self.canvas, 1, wx.TOP | wx.LEFT | wx.EXPAND)
            # Capture the paint message
            wx.EVT_PAINT(self, self.OnPaint)

            self.toolbar = MyNavigationToolbar(self.canvas, True)
            self.toolbar.Realize()
            if wx.Platform == '__WXMAC__':
                # Mac platform (OSX 10.3, MacPython) does not seem to cope with
                # having a toolbar in a sizer. This work-around gets the buttons
                # back, but at the expense of having the toolbar at the top
                self.SetToolBar(self.toolbar)
            else:
                # On Windows platform, default window size is incorrect, so set
                # toolbar width to figure width.
                tw, th = self.toolbar.GetSizeTuple()
                fw, fh = self.canvas.GetSizeTuple()
                # By adding toolbar in sizer, we are able to put it at the bottom
                # of the frame - so appearance is closer to GTK version.
                # As noted above, doesn't work for Mac.
                self.toolbar.SetSize(wx.Size(fw, th))
                self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)

            # update the axes menu on the toolbar
            self.toolbar.update()
            self.SetSizer(self.sizer)
            self.Fit()

        def OnPaint(self, event):
            self.canvas.draw()
            event.Skip()

    #-------------------------------------------------------------------------------
    # Script Definitions

    if __name__ == '__main__':
        app = wx.App(False)
        frame = wx.Frame(None,size=wx.Size(900, 800))
        panel=MatplotlibWxPanel(id=1, name='MatplotlibWxPanel',
                  parent=frame, pos=wx.Point(350, 204), size=wx.Size(200, 800),
                  style=wx.TAB_TRAVERSAL)
        sizer=wx.BoxSizer()
        sizer.Add(panel,1,wx.EXPAND,2)
        frame.SetSizerAndFit(sizer)
        frame.SetSize(wx.Size(1000, 800))
        frame.Show()
        app.MainLoop()

## Functions

def rand(

...)

rand(d0, d1, ..., dn)

Random values in a given shape.

Create an array of the given shape and populate it with random samples from a uniform distribution over `[0, 1)`.

## Parameters

d0, d1, ..., dn : int, optional The dimensions of the returned array, should all be positive. If no argument is given a single Python float is returned.

## Returns

out : ndarray, shape `(d0, d1, ..., dn)` Random values.

## See Also

random

## Notes

This is a convenience function. If you want an interface that takes a shape-tuple as the first argument, refer to np.random.random_sample .

## Examples

> > > np.random.rand(3,2) array([[ 0.14022471, 0.96360618], #random [ 0.37601032, 0.25528411], #random [ 0.49313049, 0.94909878]]) #random

## Classes

class MatplotlibWxPanel

This is a wx.Panel that shows a plot with a custom toolbar

Show source ≡

    class MatplotlibWxPanel(wx.Panel):
        """ This is a wx.Panel that shows a plot with a custom toolbar"""
        def __init__(self, parent, id, pos, size, style, name):
            wx.Panel.__init__(self, parent, id, pos, size, style, name)

            self.SetBackgroundColour(wx.NamedColour("WHITE"))

            self.figure = Figure(figsize=(5,4), dpi=100)
            self.axes = self.figure.add_subplot(111)
            t = arange(0.0,3.0,0.01)
            s = sin(2*pi*t)

            self.axes.plot(t,s)

            self.canvas = FigureCanvas(self, -1, self.figure)

            self.sizer = wx.BoxSizer(wx.VERTICAL)
            self.sizer.Add(self.canvas, 1, wx.TOP | wx.LEFT | wx.EXPAND)
            # Capture the paint message
            wx.EVT_PAINT(self, self.OnPaint)

            self.toolbar = MyNavigationToolbar(self.canvas, True)
            self.toolbar.Realize()
            if wx.Platform == '__WXMAC__':
                # Mac platform (OSX 10.3, MacPython) does not seem to cope with
                # having a toolbar in a sizer. This work-around gets the buttons
                # back, but at the expense of having the toolbar at the top
                self.SetToolBar(self.toolbar)
            else:
                # On Windows platform, default window size is incorrect, so set
                # toolbar width to figure width.
                tw, th = self.toolbar.GetSizeTuple()
                fw, fh = self.canvas.GetSizeTuple()
                # By adding toolbar in sizer, we are able to put it at the bottom
                # of the frame - so appearance is closer to GTK version.
                # As noted above, doesn't work for Mac.
                self.toolbar.SetSize(wx.Size(fw, th))
                self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)

            # update the axes menu on the toolbar
            self.toolbar.update()
            self.SetSizer(self.sizer)
            self.Fit()

        def OnPaint(self, event):
            self.canvas.draw()
            event.Skip()

### Ancestors (in MRO)

- MatplotlibWxPanel
- wx._core.Panel
- wx._core.Window
- wx._core.WindowBase
- wx._core.EvtHandler
- wx._core.Object
- wx._core.Trackable
- sip.wrapper
- sip.simplewrapper
- builtins.object

### Class variables

var ChildrenRepositioningGuard

### Static methods

def __init__(

self, parent, id, pos, size, style, name)

Initialize self. See help(type(self)) for accurate signature.

Show source ≡

    def __init__(self, parent, id, pos, size, style, name):
        wx.Panel.__init__(self, parent, id, pos, size, style, name)
        self.SetBackgroundColour(wx.NamedColour("WHITE"))
        self.figure = Figure(figsize=(5,4), dpi=100)
        self.axes = self.figure.add_subplot(111)
        t = arange(0.0,3.0,0.01)
        s = sin(2*pi*t)
        self.axes.plot(t,s)
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.TOP | wx.LEFT | wx.EXPAND)
        # Capture the paint message
        wx.EVT_PAINT(self, self.OnPaint)
        self.toolbar = MyNavigationToolbar(self.canvas, True)
        self.toolbar.Realize()
        if wx.Platform == '__WXMAC__':
            # Mac platform (OSX 10.3, MacPython) does not seem to cope with
            # having a toolbar in a sizer. This work-around gets the buttons
            # back, but at the expense of having the toolbar at the top
            self.SetToolBar(self.toolbar)
        else:
            # On Windows platform, default window size is incorrect, so set
            # toolbar width to figure width.
            tw, th = self.toolbar.GetSizeTuple()
            fw, fh = self.canvas.GetSizeTuple()
            # By adding toolbar in sizer, we are able to put it at the bottom
            # of the frame - so appearance is closer to GTK version.
            # As noted above, doesn't work for Mac.
            self.toolbar.SetSize(wx.Size(fw, th))
            self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        # update the axes menu on the toolbar
        self.toolbar.update()
        self.SetSizer(self.sizer)
        self.Fit()

def Bind(

self, event, handler, source=None, id=-1, id2=-1)

Bind an event to an event handler.

:param event: One of the `EVT_*` event binder objects that specifies the type of event to bind.

:param handler: A callable object to be invoked when the event is delivered to self. Pass `None` to disconnect an event handler.

:param source: Sometimes the event originates from a different window than self, but you still want to catch it in self. (For example, a button event delivered to a frame.) By passing the source of the event, the event handling system is able to differentiate between the same event type from different controls.

:param id: Used to spcify the event source by ID instead of instance.

:param id2: Used when it is desirable to bind a handler to a range of IDs, such as with EVT_MENU_RANGE.

Show source ≡

    def _EvtHandler_Bind(self, event, handler, source=None, id=wx.ID_ANY, id2=wx.ID_ANY):
        """
        Bind an event to an event handler.

        :param event: One of the ``EVT_*`` event binder objects that
                      specifies the type of event to bind.

        :param handler: A callable object to be invoked when the
                        event is delivered to self.  Pass ``None`` to
                        disconnect an event handler.

        :param source: Sometimes the event originates from a
                       different window than self, but you still
                       want to catch it in self.  (For example, a
                       button event delivered to a frame.)  By
                       passing the source of the event, the event
                       handling system is able to differentiate
                       between the same event type from different
                       controls.

        :param id: Used to spcify the event source by ID instead
                   of instance.

        :param id2: Used when it is desirable to bind a handler
                    to a range of IDs, such as with EVT_MENU_RANGE.
        """
        assert isinstance(event, wx.PyEventBinder)
        assert callable(handler) or handler is None
        assert source is None or hasattr(source, 'GetId')
        if source is not None:
            id  = source.GetId()
        event.Bind(self, id, id2, handler)

def ConvertDialogPointToPixels(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def ConvertDialogSizeToPixels(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def DLG_UNIT(

self, dlg_unit)

A convenience wrapper for :meth:`ConvertDialogToPixels`.

Show source ≡

    def _Window_DLG_UNIT(self, dlg_unit):
        """
        A convenience wrapper for :meth:`ConvertDialogToPixels`.
        """
        is_wxType = isinstance(dlg_unit, (wx.Size, wx.Point))
        pix = self.ConvertDialogToPixels(dlg_unit)
        if not is_wxType:
            pix = tuple(pix)
        return pix

def DestroyLater(

self)

Schedules the window to be destroyed in the near future.

This should be used whenever Destroy could happen too soon, such as when there may still be events for this window or its children waiting in the event queue.

Show source ≡

    def _Window_DestroyLater(self):
        """
        Schedules the window to be destroyed in the near future.

        This should be used whenever Destroy could happen too soon, such
        as when there may still be events for this window or its children
        waiting in the event queue.
        """
        self.Hide()
        wx.GetApp().ScheduleForDestruction(self)

def GetPositionTuple(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def GetSizeTuple(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def GetVirtualSizeTuple(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def MoveXY(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def OnPaint(

self, event)

Show source ≡

    def OnPaint(self, event):
        self.canvas.draw()
        event.Skip()

def PostCreate(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def SetClientRect(

self, rect)

Show source ≡

    def _Window_SetClientRect(self, rect):
        return self.SetClientSize(rect)

def SetDimensions(

*args, **kw)

SetDimensions(x, y, width, height, sizeFlags=SIZE_AUTO)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def SetRect(

self, rect)

Show source ≡

    def _Window_SetRect(self, rect):
        return self.SetSize(rect)

def SetSizeHintsSz(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def SetSizeWH(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def SetToolTipString(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def SetVirtualSizeWH(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def Unbind(

self, event, source=None, id=-1, id2=-1, handler=None)

Disconnects the event handler binding for event from `self`. Returns `True` if successful.

Show source ≡

    def _EvtHandler_Unbind(self, event, source=None, id=wx.ID_ANY, id2=wx.ID_ANY, handler=None):
        """
        Disconnects the event handler binding for event from `self`.
        Returns ``True`` if successful.
        """
        if source is not None:
            id  = source.GetId()
        return event.Unbind(self, id, id2, handler)

### Instance variables

var AcceleratorTable

GetAcceleratorTable() -> AcceleratorTable

Gets the accelerator table for this window.

var AutoLayout

GetAutoLayout() -> bool

Returns the sizer of which this window is a member, if any, otherwise NULL.

var BackgroundColour

GetBackgroundColour() -> Colour

Returns the background colour of the window.

var BackgroundStyle

GetBackgroundStyle() -> BackgroundStyle

Returns the background style of the window.

var BestSize

GetBestSize() -> Size

This functions returns the best acceptable minimal size for the window.

var BestVirtualSize

GetBestVirtualSize() -> Size

Return the largest of ClientSize and BestSize (as determined by a sizer, interior children, or other means)

var Border

GetBorder(flags) -> Border GetBorder() -> Border

Get the window border style from the given flags: this is different from simply doing flags & wxBORDER_MASK because it uses GetDefaultBorder() to translate wxBORDER_DEFAULT to something reasonable.

var Caret

GetCaret() -> Caret

Returns the caret() associated with the window.

var CharHeight

GetCharHeight() -> int

Returns the character height for this window.

var CharWidth

GetCharWidth() -> int

Returns the average character width for this window.

var Children

GetChildren() -> WindowList

Returns a reference to the list of the window's children.

var ClassInfo

GetClassInfo() -> ClassInfo

This virtual function is redefined for every class that requires run- time type information, when using the wxDECLARE_CLASS macro (or similar).

var ClassName

GetClassName() -> Char

Returns the class name of the C++ class using wxRTTI.

var ClientAreaOrigin

GetClientAreaOrigin() -> Point

Get the origin of the client area of the window relative to the window top left corner (the client area may be shifted because of the borders, scrollbars, other decorations...)

var ClientRect

GetClientRect() -> Rect

Get the client rectangle in window (i.e. client) coordinates.

var ClientSize

GetClientSize() -> Size

Returns the size of the window 'client area' in pixels.

var Constraints

GetConstraints() -> LayoutConstraints

Returns a pointer to the window's layout constraints, or NULL if there are none.

var ContainingSizer

GetContainingSizer() -> Sizer

Returns the sizer of which this window is a member, if any, otherwise NULL.

var Cursor

GetCursor() -> Cursor

Return the cursor associated with this window.

var DefaultAttributes

GetDefaultAttributes() -> VisualAttributes

Currently this is the same as calling wxWindow::GetClassDefaultAttributes(wxWindow::GetWindowVariant()).

var DropTarget

GetDropTarget() -> DropTarget

Returns the associated drop target, which may be NULL.

var EffectiveMinSize

GetEffectiveMinSize() -> Size

Merges the window's best size into the min size and returns the result.

var Enabled

IsEnabled() -> bool

Returns true if the window is enabled, i.e. if it accepts user input, false otherwise.

var EventHandler

GetEventHandler() -> EvtHandler

Returns the event handler for this window.

var EvtHandlerEnabled

GetEvtHandlerEnabled() -> bool

Returns true if the event handler is enabled, false otherwise.

var ExtraStyle

GetExtraStyle() -> long

Returns the extra style bits for the window.

var Font

GetFont() -> Font

Returns the font for this window.

var ForegroundColour

GetForegroundColour() -> Colour

Returns the foreground colour of the window.

var GrandParent

GetGrandParent() -> Window

Returns the grandparent of a window, or NULL if there isn't one.

var Handle

GetHandle() -> UIntPtr

Returns the platform-specific handle of the physical window.

var HelpText

GetHelpText() -> String

Gets the help text to be used as context-sensitive help for this window.

var Id

GetId() -> WindowID

Returns the identifier of the window.

var Label

GetLabel() -> String

Generic way of getting a label from any window, for identification purposes.

var LayoutDirection

GetLayoutDirection() -> LayoutDirection

Returns the layout direction for this window, Note that wxLayout_Default is returned if layout direction is not supported.

var MaxClientSize

GetMaxClientSize() -> Size

Returns the maximum size of window's client area.

var MaxHeight

GetMaxHeight() -> int

Returns the vertical component of window maximal size.

var MaxSize

GetMaxSize() -> Size

Returns the maximum size of the window.

var MaxWidth

GetMaxWidth() -> int

Returns the horizontal component of window maximal size.

var MinClientSize

GetMinClientSize() -> Size

Returns the minimum size of window's client area, an indication to the sizer layout mechanism that this is the minimum required size of its client area.

var MinHeight

GetMinHeight() -> int

Returns the vertical component of window minimal size.

var MinSize

GetMinSize() -> Size

Returns the minimum size of the window, an indication to the sizer layout mechanism that this is the minimum required size.

var MinWidth

GetMinWidth() -> int

Returns the horizontal component of window minimal size.

var Name

GetName() -> String

Returns the window's name.

var NextHandler

GetNextHandler() -> EvtHandler

Returns the pointer to the next handler in the chain.

var Parent

GetParent() -> Window

Returns the parent of the window, or NULL if there is no parent.

var Position

GetPosition() -> Point

This gets the position of the window in pixels, relative to the parent window for the child windows or relative to the display origin for the top level windows.

var PreviousHandler

GetPreviousHandler() -> EvtHandler

Returns the pointer to the previous handler in the chain.

var Rect

GetRect() -> Rect

Returns the position and size of the window as a wxRect object.

var RefData

GetRefData() -> ObjectRefData

Returns the wxObject::m_refData pointer, i.e. the data referenced by this object.

var ScreenPosition

GetScreenPosition() -> Point

Returns the window position in screen coordinates, whether the window is a child window or a top level one.

var ScreenRect

GetScreenRect() -> Rect

Returns the position and size of the window on the screen as a wxRect object.

var Shown

IsShown() -> bool

Returns true if the window is shown, false if it has been hidden.

var Size

GetSize() -> Size

Returns the size of the entire window in pixels, including title bar, border, scrollbars, etc.

var Sizer

GetSizer() -> Sizer

Returns the sizer associated with the window by a previous call to SetSizer(), or NULL.

var ThemeEnabled

GetThemeEnabled() -> bool

Clears the window by filling it with the current background colour.

var ToolTip

GetToolTip() -> ToolTip

Get the associated tooltip or NULL if none.

var TopLevel

IsTopLevel() -> bool

Returns true if the given window is a top-level one.

var TopLevelParent

GetTopLevelParent() -> Window

Returns the first ancestor of this window which is a top-level window.

var UpdateClientRect

GetUpdateClientRect() -> Rect

Get the update rectangle bounding box in client coords.

var UpdateRegion

GetUpdateRegion() -> Region

Returns the region specifying which parts of the window have been damaged.

var Validator

GetValidator() -> Validator

Validator functions.

var VirtualSize

GetVirtualSize() -> Size

This gets the virtual size of the window in pixels.

var WindowStyle

GetWindowStyle() -> long

See GetWindowStyleFlag() for more info.

var WindowStyleFlag

GetWindowStyleFlag() -> long

Gets the window style that was passed to the constructor or Create() method.

var WindowVariant

GetWindowVariant() -> WindowVariant

Returns the value previously passed to SetWindowVariant().

var axes

var canvas

var figure

var sizer

var toolbar

class MyNavigationToolbar

Extend the default wx toolbar with your own event handlers

Show source ≡

    class MyNavigationToolbar(NavigationToolbar2WxAgg):
        """
        Extend the default wx toolbar with your own event handlers
        """
        ON_CUSTOM = wx.NewId()
        def __init__(self, canvas, cankill):
            NavigationToolbar2WxAgg.__init__(self, canvas)

            # for simplicity I'm going to reuse a bitmap from wx, you'll
            # probably want to add your own.wx.ART_FOLDER_OPEN
            #wx.ArtProvider.GetBitmap(wx.ART_FOLDER_OPEN) is the stock icons command
            self.AddSimpleTool(self.ON_CUSTOM, wx.ArtProvider.GetBitmap(wx.ART_FOLDER_OPEN),
                               'Plot measurement', 'Plot an XML data file')
            wx.EVT_TOOL(self, self.ON_CUSTOM, self._on_custom)

            # self.AddSimpleTool(self.ON_CUSTOM, wx.ArtProvider.GetBitmap(wx.ART_FOLDER_OPEN),
            #                    'Click me', 'Activate custom contol')
            #wx.EVT_TOOL(self, self.ON_CUSTOM, self._on_custom)

        def _on_custom(self, evt):
            # add some text to the axes in a random location in axes (0,1)
            # coords) with a random color

    ##        # get the axes
    ##        ax = self.canvas.figure.axes[0]
    ##
    ##        # generate a random location can color
    ##        x,y = tuple(rand(2))
    ##        rgb = tuple(rand(3))
    ##
    ##        # add the text and draw
    ##        ax.text(x, y, 'You clicked me',
    ##                transform=ax.transAxes,
    ##                color=rgb)
    ##        self.canvas.draw()
            # This is a stub out for a file chooser to plot.
            dlg = wx.FileDialog(self, 'Choose a file', TESTS_DIRECTORY, '', '*.*', wx.OPEN)
            try:
                if dlg.ShowModal() == wx.ID_OK:
                    filename = dlg.GetPath()
                    try:
                        data_sheet=DataTable(filename)
                        self.canvas.figure.clear()
                        self.axes = self.canvas.figure.add_subplot(111)
                        ax = self.canvas.figure.axes[0]
                        # This needs to be generalized with a chooser so that things with
                        # lots of columns can be plotted
                        #print(data_sheet.get_attribute_names())

                        if 'Current' in data_sheet.get_attribute_names():
                            y_name='Current'
                        if 'Voltage' in data_sheet.get_attribute_names():
                            x_name='Voltage'

                        else:
                            y_name=data_sheet.get_attribute_names()[0]
                            x_name=data_sheet.get_attribute_names()[1]
                        params={'axes.labelsize': 18,"font.size":18,
                        'legend.fontsize': 18,
                        'xtick.labelsize': 18,
                        'ytick.labelsize': 18,
                        }

                        matplotlib.rcParams.update(params)
                        self.axes.xaxis.set_major_formatter(ticker.ScalarFormatter(useOffset=True))
                        self.axes.yaxis.set_major_formatter(ticker.ScalarFormatter(useOffset=True))
                        #print(x_name,y_name)
                        self.axes.set_xlabel(x_name,fontsize=20)
                        self.axes.set_ylabel(y_name,fontsize=20)
                        x_data=np.array([float(x) for x in data_sheet.to_list(x_name)])
                        y_data=np.array([float(x) for x in data_sheet.to_list(y_name)])
                        ax.plot(x_data,y_data)
                        self.canvas.draw()
                        # Set the Title
                        try:
                            self.Parent.Parent.SetTitle(data_sheet.path)
                        except:
                            pass
                        self.Update()
                    except:
                        raise

            finally:
                dlg.Destroy()
            evt.Skip()

### Ancestors (in MRO)

- MyNavigationToolbar
- matplotlib.backends.backend_wx.NavigationToolbar2Wx
- matplotlib.backend_bases.NavigationToolbar2
- wx._core.ToolBar
- wx._core.Control
- wx._core.Window
- wx._core.WindowBase
- wx._core.EvtHandler
- wx._core.Object
- wx._core.Trackable
- sip.wrapper
- sip.simplewrapper
- builtins.object

### Class variables

var ChildrenRepositioningGuard

var ON_CUSTOM

var toolitems

### Static methods

def __init__(

self, canvas, cankill)

Initialize self. See help(type(self)) for accurate signature.

Show source ≡

    def __init__(self, canvas, cankill):
        NavigationToolbar2WxAgg.__init__(self, canvas)
        # for simplicity I'm going to reuse a bitmap from wx, you'll
        # probably want to add your own.wx.ART_FOLDER_OPEN
        #wx.ArtProvider.GetBitmap(wx.ART_FOLDER_OPEN) is the stock icons command
        self.AddSimpleTool(self.ON_CUSTOM, wx.ArtProvider.GetBitmap(wx.ART_FOLDER_OPEN),
                           'Plot measurement', 'Plot an XML data file')
        wx.EVT_TOOL(self, self.ON_CUSTOM, self._on_custom)

def AddLabelTool(

*args, **kw)

Old style method to add a tool in the toolbar.

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def AddSimpleTool(

*args, **kw)

Old style method to add a tool to the toolbar.

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def Bind(

self, event, handler, source=None, id=-1, id2=-1)

Bind an event to an event handler.

:param event: One of the `EVT_*` event binder objects that specifies the type of event to bind.

:param handler: A callable object to be invoked when the event is delivered to self. Pass `None` to disconnect an event handler.

:param source: Sometimes the event originates from a different window than self, but you still want to catch it in self. (For example, a button event delivered to a frame.) By passing the source of the event, the event handling system is able to differentiate between the same event type from different controls.

:param id: Used to spcify the event source by ID instead of instance.

:param id2: Used when it is desirable to bind a handler to a range of IDs, such as with EVT_MENU_RANGE.

Show source ≡

    def _EvtHandler_Bind(self, event, handler, source=None, id=wx.ID_ANY, id2=wx.ID_ANY):
        """
        Bind an event to an event handler.

        :param event: One of the ``EVT_*`` event binder objects that
                      specifies the type of event to bind.

        :param handler: A callable object to be invoked when the
                        event is delivered to self.  Pass ``None`` to
                        disconnect an event handler.

        :param source: Sometimes the event originates from a
                       different window than self, but you still
                       want to catch it in self.  (For example, a
                       button event delivered to a frame.)  By
                       passing the source of the event, the event
                       handling system is able to differentiate
                       between the same event type from different
                       controls.

        :param id: Used to spcify the event source by ID instead
                   of instance.

        :param id2: Used when it is desirable to bind a handler
                    to a range of IDs, such as with EVT_MENU_RANGE.
        """
        assert isinstance(event, wx.PyEventBinder)
        assert callable(handler) or handler is None
        assert source is None or hasattr(source, 'GetId')
        if source is not None:
            id  = source.GetId()
        event.Bind(self, id, id2, handler)

def ConvertDialogPointToPixels(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def ConvertDialogSizeToPixels(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def DLG_UNIT(

self, dlg_unit)

A convenience wrapper for :meth:`ConvertDialogToPixels`.

Show source ≡

    def _Window_DLG_UNIT(self, dlg_unit):
        """
        A convenience wrapper for :meth:`ConvertDialogToPixels`.
        """
        is_wxType = isinstance(dlg_unit, (wx.Size, wx.Point))
        pix = self.ConvertDialogToPixels(dlg_unit)
        if not is_wxType:
            pix = tuple(pix)
        return pix

def DestroyLater(

self)

Schedules the window to be destroyed in the near future.

This should be used whenever Destroy could happen too soon, such as when there may still be events for this window or its children waiting in the event queue.

Show source ≡

    def _Window_DestroyLater(self):
        """
        Schedules the window to be destroyed in the near future.

        This should be used whenever Destroy could happen too soon, such
        as when there may still be events for this window or its children
        waiting in the event queue.
        """
        self.Hide()
        wx.GetApp().ScheduleForDestruction(self)

def GetPositionTuple(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def GetSizeTuple(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def GetVirtualSizeTuple(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def InsertLabelTool(

*args, **kw)

Old style method to insert a tool in the toolbar.

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def InsertSimpleTool(

*args, **kw)

Old style method to insert a tool in the toolbar.

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def MoveXY(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def PostCreate(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def SetClientRect(

self, rect)

Show source ≡

    def _Window_SetClientRect(self, rect):
        return self.SetClientSize(rect)

def SetDimensions(

*args, **kw)

SetDimensions(x, y, width, height, sizeFlags=SIZE_AUTO)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def SetRect(

self, rect)

Show source ≡

    def _Window_SetRect(self, rect):
        return self.SetSize(rect)

def SetSizeHintsSz(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def SetSizeWH(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def SetToolTipString(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def SetVirtualSizeWH(

*args, **kw)

Show source ≡

    def deprecated_func(*args, **kw):
        warnings.warn("Call to deprecated item%s. %s" % (name, msg),
                      wxPyDeprecationWarning, stacklevel=2)
        if not kw:
            return item(*args)
        return item(*args, **kw)

def Unbind(

self, event, source=None, id=-1, id2=-1, handler=None)

Disconnects the event handler binding for event from `self`. Returns `True` if successful.

Show source ≡

    def _EvtHandler_Unbind(self, event, source=None, id=wx.ID_ANY, id2=wx.ID_ANY, handler=None):
        """
        Disconnects the event handler binding for event from `self`.
        Returns ``True`` if successful.
        """
        if source is not None:
            id  = source.GetId()
        return event.Unbind(self, id, id2, handler)

def back(

self, *args)

move back up the view lim stack

Show source ≡

    def back(self, *args):
        """move back up the view lim stack"""
        self._nav_stack.back()
        self.set_history_buttons()
        self._update_view()

def configure_subplots(

self, evt)

Show source ≡

    def configure_subplots(self, evt):
        frame = wx.Frame(None, -1, "Configure subplots")
        toolfig = Figure((6, 3))
        canvas = self.get_canvas(frame, toolfig)
        # Create a figure manager to manage things
        figmgr = FigureManager(canvas, 1, frame)
        # Now put all into a sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        frame.SetSizer(sizer)
        frame.Fit()
        tool = SubplotTool(self.canvas.figure, toolfig)
        frame.Show()

def drag_pan(

self, event)

Callback for dragging in pan/zoom mode.

Show source ≡

    def drag_pan(self, event):
        """Callback for dragging in pan/zoom mode."""
        for a, ind in self._xypress:
            #safer to use the recorded button at the press than current button:
            #multiple button can get pressed during motion...
            a.drag_pan(self._button_pressed, event.key, event.x, event.y)
        self.canvas.draw_idle()

def drag_zoom(

self, event)

Callback for dragging in zoom mode.

Show source ≡

    def drag_zoom(self, event):
        """Callback for dragging in zoom mode."""
        if self._xypress:
            x, y = event.x, event.y
            lastx, lasty, a, ind, view = self._xypress[0]
            (x1, y1), (x2, y2) = np.clip(
                [[lastx, lasty], [x, y]], a.bbox.min, a.bbox.max)
            if self._zoom_mode == "x":
                y1, y2 = a.bbox.intervaly
            elif self._zoom_mode == "y":
                x1, x2 = a.bbox.intervalx
            self.draw_rubberband(event, x1, y1, x2, y2)

def draw(

self)

Redraw the canvases, update the locators.

Show source ≡

    def draw(self):
        """Redraw the canvases, update the locators."""
        for a in self.canvas.figure.get_axes():
            xaxis = getattr(a, 'xaxis', None)
            yaxis = getattr(a, 'yaxis', None)
            locators = []
            if xaxis is not None:
                locators.append(xaxis.get_major_locator())
                locators.append(xaxis.get_minor_locator())
            if yaxis is not None:
                locators.append(yaxis.get_major_locator())
                locators.append(yaxis.get_minor_locator())
            for loc in locators:
                loc.refresh()
        self.canvas.draw_idle()

def draw_rubberband(

self, event, x0, y0, x1, y1)

Draw a rectangle rubberband to indicate zoom limits.

Note that it is not guaranteed that `x0 <= x1` and `y0 <= y1`.

Show source ≡

    def draw_rubberband(self, event, x0, y0, x1, y1):
        if self.retinaFix:  # On Macs, use the following code
            # wx.DCOverlay does not work properly on Retina displays.
            rubberBandColor = '#C0C0FF'
            if self.prevZoomRect:
                self.prevZoomRect.pop(0).remove()
            self.canvas.restore_region(self.savedRetinaImage)
            X0, X1 = self.zoomStartX, event.xdata
            Y0, Y1 = self.zoomStartY, event.ydata
            lineX = (X0, X0, X1, X1, X0)
            lineY = (Y0, Y1, Y1, Y0, Y0)
            self.prevZoomRect = self.zoomAxes.plot(
                lineX, lineY, '-', color=rubberBandColor)
            self.zoomAxes.draw_artist(self.prevZoomRect[0])
            self.canvas.blit(self.zoomAxes.bbox)
            return
        # Use an Overlay to draw a rubberband-like bounding box.
        dc = wx.ClientDC(self.canvas)
        odc = wx.DCOverlay(self.wxoverlay, dc)
        odc.Clear()
        # Mac's DC is already the same as a GCDC, and it causes
        # problems with the overlay if we try to use an actual
        # wx.GCDC so don't try it.
        if 'wxMac' not in wx.PlatformInfo:
            dc = wx.GCDC(dc)
        height = self.canvas.figure.bbox.height
        y1 = height - y1
        y0 = height - y0
        if y1 < y0:
            y0, y1 = y1, y0
        if x1 < x0:
            x0, x1 = x1, x0
        w = x1 - x0
        h = y1 - y0
        rect = wx.Rect(x0, y0, w, h)
        rubberBandColor = '#C0C0FF'  # or load from config?
        # Set a pen for the border
        color = wxc.NamedColour(rubberBandColor)
        dc.SetPen(wx.Pen(color, 1))
        # use the same color, plus alpha for the brush
        r, g, b, a = color.Get(True)
        color.Set(r, g, b, 0x60)
        dc.SetBrush(wx.Brush(color))
        if wxc.is_phoenix:
            dc.DrawRectangle(rect)
        else:
            dc.DrawRectangleRect(rect)

def dynamic_update(

*args, **kwargs)

.. deprecated:: 2.1 The dynamic_update function was deprecated in version 2.1. Use canvas.draw_idle instead.

\

Show source ≡

    @cbook.deprecated("2.1", alternative="canvas.draw_idle")
    def dynamic_update(self):
        d = self._idle
        self._idle = False
        if d:
            self.canvas.draw()
            self._idle = True

def forward(

self, *args)

Move forward in the view lim stack.

Show source ≡

    def forward(self, *args):
        """Move forward in the view lim stack."""
        self._nav_stack.forward()
        self.set_history_buttons()
        self._update_view()

def get_canvas(

self, frame, fig)

Show source ≡

    def get_canvas(self, frame, fig):
        return type(self.canvas)(frame, -1, fig)

def home(

self, *args)

Restore the original view.

Show source ≡

    def home(self, *args):
        """Restore the original view."""
        self._nav_stack.home()
        self.set_history_buttons()
        self._update_view()

def mouse_move(

self, event)

Show source ≡

    def mouse_move(self, event):
        self._set_cursor(event)
        if event.inaxes and event.inaxes.get_navigate():
            try:
                s = event.inaxes.format_coord(event.xdata, event.ydata)
            except (ValueError, OverflowError):
                pass
            else:
                artists = [a for a in event.inaxes.mouseover_set
                           if a.contains(event) and a.get_visible()]
                if artists:
                    a = cbook._topmost_artist(artists)
                    if a is not event.inaxes.patch:
                        data = a.get_cursor_data(event)
                        if data is not None:
                            s += ' [%s]' % a.format_cursor_data(data)
                if len(self.mode):
                    self.set_message('%s, %s' % (self.mode, s))
                else:
                    self.set_message(s)
        else:
            self.set_message(self.mode)

def pan(

self, *args)

Activate the pan/zoom tool. pan with left button, zoom with right

Show source ≡

    def pan(self, *args):
        self.ToggleTool(self.wx_ids['Zoom'], False)
        NavigationToolbar2.pan(self, *args)

def press(

self, event)

Called whenever a mouse button is pressed.

Show source ≡

    def press(self, event):
        if self._active == 'ZOOM':
            if not self.retinaFix:
                self.wxoverlay = wx.Overlay()
            else:
                if event.inaxes is not None:
                    self.savedRetinaImage = self.canvas.copy_from_bbox(
                        event.inaxes.bbox)
                    self.zoomStartX = event.xdata
                    self.zoomStartY = event.ydata
                    self.zoomAxes = event.inaxes

def press_pan(

self, event)

Callback for mouse button press in pan/zoom mode.

Show source ≡

    def press_pan(self, event):
        """Callback for mouse button press in pan/zoom mode."""
        if event.button == 1:
            self._button_pressed = 1
        elif event.button == 3:
            self._button_pressed = 3
        else:
            self._button_pressed = None
            return
        if self._nav_stack() is None:
            # set the home button to this view
            self.push_current()
        x, y = event.x, event.y
        self._xypress = []
        for i, a in enumerate(self.canvas.figure.get_axes()):
            if (x is not None and y is not None and a.in_axes(event) and
                    a.get_navigate() and a.can_pan()):
                a.start_pan(x, y, event.button)
                self._xypress.append((a, i))
                self.canvas.mpl_disconnect(self._idDrag)
                self._idDrag = self.canvas.mpl_connect('motion_notify_event',
                                                       self.drag_pan)
        self.press(event)

def press_zoom(

self, event)

Callback for mouse button press in zoom to rect mode.

Show source ≡

    def press_zoom(self, event):
        """Callback for mouse button press in zoom to rect mode."""
        # If we're already in the middle of a zoom, pressing another
        # button works to "cancel"
        if self._ids_zoom != []:
            for zoom_id in self._ids_zoom:
                self.canvas.mpl_disconnect(zoom_id)
            self.release(event)
            self.draw()
            self._xypress = None
            self._button_pressed = None
            self._ids_zoom = []
            return
        if event.button == 1:
            self._button_pressed = 1
        elif event.button == 3:
            self._button_pressed = 3
        else:
            self._button_pressed = None
            return
        if self._nav_stack() is None:
            # set the home button to this view
            self.push_current()
        x, y = event.x, event.y
        self._xypress = []
        for i, a in enumerate(self.canvas.figure.get_axes()):
            if (x is not None and y is not None and a.in_axes(event) and
                    a.get_navigate() and a.can_zoom()):
                self._xypress.append((x, y, a, i, a._get_view()))
        id1 = self.canvas.mpl_connect('motion_notify_event', self.drag_zoom)
        id2 = self.canvas.mpl_connect('key_press_event',
                                      self._switch_on_zoom_mode)
        id3 = self.canvas.mpl_connect('key_release_event',
                                      self._switch_off_zoom_mode)
        self._ids_zoom = id1, id2, id3
        self._zoom_mode = event.key
        self.press(event)

def push_current(

self)

Push the current view limits and position onto the stack.

Show source ≡

    def push_current(self):
        """Push the current view limits and position onto the stack."""
        self._nav_stack.push(
            WeakKeyDictionary(
                {ax: (ax._get_view(),
                      # Store both the original and modified positions.
                      (ax.get_position(True).frozen(),
                       ax.get_position().frozen()))
                 for ax in self.canvas.figure.axes}))
        self.set_history_buttons()

def release(

self, event)

Callback for mouse button release.

Show source ≡

    def release(self, event):
        if self._active == 'ZOOM':
            # When the mouse is released we reset the overlay and it
            # restores the former content to the window.
            if not self.retinaFix:
                self.wxoverlay.Reset()
                del self.wxoverlay
            else:
                del self.savedRetinaImage
                if self.prevZoomRect:
                    self.prevZoomRect.pop(0).remove()
                    self.prevZoomRect = None
                if self.zoomAxes:
                    self.zoomAxes = None

def release_pan(

self, event)

Callback for mouse button release in pan/zoom mode.

Show source ≡

    def release_pan(self, event):
        """Callback for mouse button release in pan/zoom mode."""
        if self._button_pressed is None:
            return
        self.canvas.mpl_disconnect(self._idDrag)
        self._idDrag = self.canvas.mpl_connect(
            'motion_notify_event', self.mouse_move)
        for a, ind in self._xypress:
            a.end_pan()
        if not self._xypress:
            return
        self._xypress = []
        self._button_pressed = None
        self.push_current()
        self.release(event)
        self.draw()

def release_zoom(

self, event)

Callback for mouse button release in zoom to rect mode.

Show source ≡

    def release_zoom(self, event):
        """Callback for mouse button release in zoom to rect mode."""
        for zoom_id in self._ids_zoom:
            self.canvas.mpl_disconnect(zoom_id)
        self._ids_zoom = []
        self.remove_rubberband()
        if not self._xypress:
            return
        last_a = []
        for cur_xypress in self._xypress:
            x, y = event.x, event.y
            lastx, lasty, a, ind, view = cur_xypress
            # ignore singular clicks - 5 pixels is a threshold
            # allows the user to "cancel" a zoom action
            # by zooming by less than 5 pixels
            if ((abs(x - lastx) < 5 and self._zoom_mode!="y") or
                    (abs(y - lasty) < 5 and self._zoom_mode!="x")):
                self._xypress = None
                self.release(event)
                self.draw()
                return
            # detect twinx,y axes and avoid double zooming
            twinx, twiny = False, False
            if last_a:
                for la in last_a:
                    if a.get_shared_x_axes().joined(a, la):
                        twinx = True
                    if a.get_shared_y_axes().joined(a, la):
                        twiny = True
            last_a.append(a)
            if self._button_pressed == 1:
                direction = 'in'
            elif self._button_pressed == 3:
                direction = 'out'
            else:
                continue
            a._set_view_from_bbox((lastx, lasty, x, y), direction,
                                  self._zoom_mode, twinx, twiny)
        self.draw()
        self._xypress = None
        self._button_pressed = None
        self._zoom_mode = None
        self.push_current()
        self.release(event)

def remove_rubberband(

self)

Remove the rubberband.

Show source ≡

    def remove_rubberband(self):
        """Remove the rubberband."""

def save_figure(

self, *args)

Save the current figure.

Show source ≡

    def save_figure(self, *args):
        # Fetch the required filename and file type.
        filetypes, exts, filter_index = self.canvas._get_imagesave_wildcards()
        default_file = self.canvas.get_default_filename()
        dlg = wx.FileDialog(self._parent, "Save to file", "", default_file,
                            filetypes,
                            wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
        dlg.SetFilterIndex(filter_index)
        if dlg.ShowModal() == wx.ID_OK:
            dirname = dlg.GetDirectory()
            filename = dlg.GetFilename()
            DEBUG_MSG(
                'Save file dir:%s name:%s' %
                (dirname, filename), 3, self)
            format = exts[dlg.GetFilterIndex()]
            basename, ext = os.path.splitext(filename)
            if ext.startswith('.'):
                ext = ext[1:]
            if ext in ('svg', 'pdf', 'ps', 'eps', 'png') and format != ext:
                # looks like they forgot to set the image type drop
                # down, going with the extension.
                warnings.warn(
                    'extension %s did not match the selected '
                    'image type %s; going with %s' %
                    (ext, format, ext), stacklevel=0)
                format = ext
            try:
                self.canvas.figure.savefig(
                    os.path.join(dirname, filename), format=format)
            except Exception as e:
                error_msg_wx(str(e))

def set_cursor(

self, cursor)

Set the current cursor to one of the :class:`Cursors` enums values.

If required by the backend, this method should trigger an update in the backend event loop after the cursor is set, as this method may be called e.g. before a long-running task during which the GUI is not updated.

Show source ≡

    def set_cursor(self, cursor):
        cursor = wxc.Cursor(cursord[cursor])
        self.canvas.SetCursor(cursor)
        self.canvas.Update()

def set_history_buttons(

self)

Enable or disable the back/forward button.

Show source ≡

    def set_history_buttons(self):
        can_backward = self._nav_stack._pos > 0
        can_forward = self._nav_stack._pos < len(self._nav_stack._elements) - 1
        self.EnableTool(self.wx_ids['Back'], can_backward)
        self.EnableTool(self.wx_ids['Forward'], can_forward)

def set_message(

self, s)

Display a message on toolbar or in status bar.

Show source ≡

    def set_message(self, s):
        if self.statbar is not None:
            self.statbar.set_function(s)

def set_status_bar(

self, statbar)

Show source ≡

    def set_status_bar(self, statbar):
        self.statbar = statbar

def update(

self)

Reset the axes stack.

Show source ≡

    def update(self):
        """Reset the axes stack."""
        self._nav_stack.clear()
        self.set_history_buttons()

def zoom(

self, *args)

Activate zoom to rect mode.

Show source ≡

    def zoom(self, *args):
        self.ToggleTool(self.wx_ids['Pan'], False)
        NavigationToolbar2.zoom(self, *args)

### Instance variables

var AcceleratorTable

GetAcceleratorTable() -> AcceleratorTable

Gets the accelerator table for this window.

var AutoLayout

GetAutoLayout() -> bool

Returns the sizer of which this window is a member, if any, otherwise NULL.

var BackgroundColour

GetBackgroundColour() -> Colour

Returns the background colour of the window.

var BackgroundStyle

GetBackgroundStyle() -> BackgroundStyle

Returns the background style of the window.

var BestSize

GetBestSize() -> Size

This functions returns the best acceptable minimal size for the window.

var BestVirtualSize

GetBestVirtualSize() -> Size

Return the largest of ClientSize and BestSize (as determined by a sizer, interior children, or other means)

var Border

GetBorder(flags) -> Border GetBorder() -> Border

Get the window border style from the given flags: this is different from simply doing flags & wxBORDER_MASK because it uses GetDefaultBorder() to translate wxBORDER_DEFAULT to something reasonable.

var Caret

GetCaret() -> Caret

Returns the caret() associated with the window.

var CharHeight

GetCharHeight() -> int

Returns the character height for this window.

var CharWidth

GetCharWidth() -> int

Returns the average character width for this window.

var Children

GetChildren() -> WindowList

Returns a reference to the list of the window's children.

var ClassInfo

GetClassInfo() -> ClassInfo

This virtual function is redefined for every class that requires run- time type information, when using the wxDECLARE_CLASS macro (or similar).

var ClassName

GetClassName() -> Char

Returns the class name of the C++ class using wxRTTI.

var ClientAreaOrigin

GetClientAreaOrigin() -> Point

Get the origin of the client area of the window relative to the window top left corner (the client area may be shifted because of the borders, scrollbars, other decorations...)

var ClientRect

GetClientRect() -> Rect

Get the client rectangle in window (i.e. client) coordinates.

var ClientSize

GetClientSize() -> Size

Returns the size of the window 'client area' in pixels.

var Constraints

GetConstraints() -> LayoutConstraints

Returns a pointer to the window's layout constraints, or NULL if there are none.

var ContainingSizer

GetContainingSizer() -> Sizer

Returns the sizer of which this window is a member, if any, otherwise NULL.

var Cursor

GetCursor() -> Cursor

Return the cursor associated with this window.

var DefaultAttributes

GetDefaultAttributes() -> VisualAttributes

Currently this is the same as calling wxWindow::GetClassDefaultAttributes(wxWindow::GetWindowVariant()).

var DropTarget

GetDropTarget() -> DropTarget

Returns the associated drop target, which may be NULL.

var EffectiveMinSize

GetEffectiveMinSize() -> Size

Merges the window's best size into the min size and returns the result.

var Enabled

IsEnabled() -> bool

Returns true if the window is enabled, i.e. if it accepts user input, false otherwise.

var EventHandler

GetEventHandler() -> EvtHandler

Returns the event handler for this window.

var EvtHandlerEnabled

GetEvtHandlerEnabled() -> bool

Returns true if the event handler is enabled, false otherwise.

var ExtraStyle

GetExtraStyle() -> long

Returns the extra style bits for the window.

var Font

GetFont() -> Font

Returns the font for this window.

var ForegroundColour

GetForegroundColour() -> Colour

Returns the foreground colour of the window.

var GrandParent

GetGrandParent() -> Window

Returns the grandparent of a window, or NULL if there isn't one.

var Handle

GetHandle() -> UIntPtr

Returns the platform-specific handle of the physical window.

var HelpText

GetHelpText() -> String

Gets the help text to be used as context-sensitive help for this window.

var Id

GetId() -> WindowID

Returns the identifier of the window.

var Label

GetLabel() -> String

Returns the control's label, as it was passed to SetLabel().

var LabelText

GetLabelText() -> String GetLabelText(label) -> String

Returns the control's label without mnemonics.

var LayoutDirection

GetLayoutDirection() -> LayoutDirection

Returns the layout direction for this window, Note that wxLayout_Default is returned if layout direction is not supported.

var Margins

GetMargins() -> Size

Returns the left/right and top/bottom margins, which are also used for inter-toolspacing.

var MaxClientSize

GetMaxClientSize() -> Size

Returns the maximum size of window's client area.

var MaxHeight

GetMaxHeight() -> int

Returns the vertical component of window maximal size.

var MaxSize

GetMaxSize() -> Size

Returns the maximum size of the window.

var MaxWidth

GetMaxWidth() -> int

Returns the horizontal component of window maximal size.

var MinClientSize

GetMinClientSize() -> Size

Returns the minimum size of window's client area, an indication to the sizer layout mechanism that this is the minimum required size of its client area.

var MinHeight

GetMinHeight() -> int

Returns the vertical component of window minimal size.

var MinSize

GetMinSize() -> Size

Returns the minimum size of the window, an indication to the sizer layout mechanism that this is the minimum required size.

var MinWidth

GetMinWidth() -> int

Returns the horizontal component of window minimal size.

var Name

GetName() -> String

Returns the window's name.

var NextHandler

GetNextHandler() -> EvtHandler

Returns the pointer to the next handler in the chain.

var Parent

GetParent() -> Window

Returns the parent of the window, or NULL if there is no parent.

var Position

GetPosition() -> Point

This gets the position of the window in pixels, relative to the parent window for the child windows or relative to the display origin for the top level windows.

var PreviousHandler

GetPreviousHandler() -> EvtHandler

Returns the pointer to the previous handler in the chain.

var Rect

GetRect() -> Rect

Returns the position and size of the window as a wxRect object.

var RefData

GetRefData() -> ObjectRefData

Returns the wxObject::m_refData pointer, i.e. the data referenced by this object.

var ScreenPosition

GetScreenPosition() -> Point

Returns the window position in screen coordinates, whether the window is a child window or a top level one.

var ScreenRect

GetScreenRect() -> Rect

Returns the position and size of the window on the screen as a wxRect object.

var Shown

IsShown() -> bool

Returns true if the window is shown, false if it has been hidden.

var Size

GetSize() -> Size

Returns the size of the entire window in pixels, including title bar, border, scrollbars, etc.

var Sizer

GetSizer() -> Sizer

Returns the sizer associated with the window by a previous call to SetSizer(), or NULL.

var ThemeEnabled

GetThemeEnabled() -> bool

Clears the window by filling it with the current background colour.

var ToolBitmapSize

GetToolBitmapSize() -> Size

Returns the size of bitmap that the toolbar expects to have.

var ToolPacking

GetToolPacking() -> int

Returns the value used for packing tools.

var ToolSeparation

GetToolSeparation() -> int

Returns the default separator size.

var ToolSize

GetToolSize() -> Size

Returns the size of a whole button, which is usually larger than a tool bitmap because of added 3D effects.

var ToolTip

GetToolTip() -> ToolTip

Get the associated tooltip or NULL if none.

var ToolsCount

GetToolsCount() -> size_t

Returns the number of tools in the toolbar.

var TopLevel

IsTopLevel() -> bool

Returns true if the given window is a top-level one.

var TopLevelParent

GetTopLevelParent() -> Window

Returns the first ancestor of this window which is a top-level window.

var UpdateClientRect

GetUpdateClientRect() -> Rect

Get the update rectangle bounding box in client coords.

var UpdateRegion

GetUpdateRegion() -> Region

Returns the region specifying which parts of the window have been damaged.

var Validator

GetValidator() -> Validator

Validator functions.

var VirtualSize

GetVirtualSize() -> Size

This gets the virtual size of the window in pixels.

var WindowStyle

GetWindowStyle() -> long

See GetWindowStyleFlag() for more info.

var WindowStyleFlag

GetWindowStyleFlag() -> long

Gets the window style that was passed to the constructor or Create() method.

var WindowVariant

GetWindowVariant() -> WindowVariant

Returns the value previously passed to SetWindowVariant().

## Module variables

var TESTS_DIRECTORY

var pi

var sin