Search code examples
pythonwxpythonmatplotlib

wxPython - resizing a MatPlotLib FigureCanvas in a ScrolledPanel


I have a figure canvas in a ScrolledPanel in a Panel. I want to change the size of the figure canvas. E.g.

mplFigure.set_figheight(1.0)
someobject.soSomethingThatResizeItAll

How can I do this?

Thanks

David

Here's my construction code.

    panel = wx.Panel(self)      # we put the scrollablePanel in the panel so later on we can do fit to window sizing too (i.e. by removing the scrollablePanel)

    # create a scrollablePanel to hold the canvas        
    scrollablePanel = ScrolledPanel(parent=panel, id=wx.ID_ANY, name="scrolledPanel", style=wx.ALWAYS_SHOW_SB)
    scrollablePanel.SetupScrolling()
    scrollablePanel.SetBackgroundColour(wx.Colour(128,128,128))

    # create mpl canvas and figure
    mplFigure = Figure(figsize=A6H, facecolor="white") #, edgecolor="black")
    mplFigureCanvas = FigureCanvasWxAgg(parent=scrollablePanel, id=wx.ID_ANY, figure=mplFigure)
    #mplFigureCanvas.SetWindowStyle=wx.SIMPLE_BORDER     # not sure if this will have any affect?
    #mplFigureCanvas.SetBackgroundColour(wx.Colour(0,0,0))

    # center the FigureCanvas inthe scrollablePanel
    sizer1 = wx.BoxSizer(wx.VERTICAL)
    sizer1.Add(mplFigureCanvas, proportion=0, flag=wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, border=8)
    sizer2 = wx.BoxSizer(wx.HORIZONTAL)
    sizer2.Add(sizer1, proportion=1, flag=wx.ALIGN_CENTER_VERTICAL)
    scrollablePanel.SetSizer(sizer2)

    # create mpl toolbar
    #mplToolbar = NavigationToolbar2Wx(mplFigureCanvas)
    #mplToolbar.Realize()                          # needed to support Windows systems

    # use another sizer to add the scrollablePanel to the main panel
    sizer = wx.BoxSizer(wx.VERTICAL)
    sizer.Add(scrollablePanel, 1, wx.LEFT | wx.EXPAND)

    #sizer.Add(mplToolbar, 0, wx.LEFT | wx.EXPAND)
    #mplToolbar.Show()

    panel.SetSizer(sizer)

Solution

  • Well I now have some horrible code that gets the result but it's not pretty.

        mplFigure.set_size_inches(sizeInInches)
        l,b,w,h = mplFigure.bbox.bounds
        w = int(math.ceil(w))
        h = int(math.ceil(h))
        mplCanvas.SetInitialSize(size=wx.Size(w, h))
        size = panel.Size
        panel.SetSize(wx.Size(size.x, size.y-1))
        panel.SetSize(wx.Size(size.x, size.y))
    

    An improvement would be welcome.

    -- DB