wxpythonmatplotlibwxnotebook

How to get layout correct for matplotlib FigureCanvas in wx.Notebook panel


I've been struggling with this for a few days now. If I don't use a wx.Notebook, I can get the FigureCanvas to size correctly within a sizer, but once I place the FigureCanvas inside of a wx.Notebook panel, the plot seems to ignore the panel sizer. It also has some sort of refresh issue, if you pull it off of the screen and back on, the plot is gone. Perhaps there is a problem with the order of commands, but I can't seem to find it. This post: How to update a plot with python and Matplotlib helped me get this far, but I can't seem to work out why the plot acts differently once I use it in a wx.Notebook.

Here's what it looks like when it first displays: http://static.inky.ws/image/2205/image.jpg

Here it is after I've pulled off the screen halfway: http://static.inky.ws/image/2206/image.jpg

#!/usr/bin/env python
import wx
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure

class MyFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self,
                          parent,
                          id=wx.ID_ANY,
                          pos=wx.DefaultPosition,
                          size=wx.Size( -1,-1 ),
                          style=wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL)

        fgSizer8 = wx.FlexGridSizer(0, 1, 0, 0)
        self.m_notebook2 = wx.Notebook(self,
                                       wx.ID_ANY,
                                       wx.DefaultPosition,
                                       wx.DefaultSize,
                                       0)

        self.m_panel8 = wx.Panel(self.m_notebook2,
                                 wx.ID_ANY,
                                 wx.DefaultPosition,
                                 wx.DefaultSize,
                                 wx.TAB_TRAVERSAL)

        bSizer20 = wx.BoxSizer(wx.VERTICAL)

        self.fig = Figure()
        self.axes = self.fig.add_subplot(111)
        self.pts = self.axes.plot([1, 2, 3], [4, 5, 7], 'ro-', picker=5)
        self.canvas = FigureCanvas(self, -1, self.fig)

        bSizer20.Add(self.canvas, 1, wx.ALL|wx.EXPAND, 5)

        self.m_panel8.SetSizer(bSizer20)
        self.m_panel8.Layout()
        bSizer20.Fit(self.m_panel8)
        self.m_notebook2.AddPage(self.m_panel8, u"a page", False)

        fgSizer8.Add(self.m_notebook2, 1, wx.EXPAND |wx.ALL, 5)

        self.SetSizer(fgSizer8)
        self.Layout()
        fgSizer8.Fit(self)

        self.Centre(wx.BOTH)

if __name__ == "__main__":
    app = wx.App(0)
    frame = MyFrame(None)
    frame.Show()
    app.MainLoop()

Solution

  • change

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

    to

    self.canvas = FigureCanvas(self.m_panel8, -1, self.fig)
    

    enter image description here