Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a FigureCanvas fit a Panel?

I'm trying to display some data using Matplotlib and wxPython. I've got a Figure that's added to a FigureCanvasWxAgg. The canvas is then added to a BoxSizer and set to wx.EXPAND|wx.ALL, the BoxSizer on its turn is set by SetSizerAndFit.

self.figure = Figure(None, dpi = 75)
self.displaycanvas = FigureCanvas(self, -1, self.figure)
self.axes = self.figure.add_subplot(111)
self.axes.imshow(self.data, interpolation="quadric")     

self.mainSizer = wx.BoxSizer()
self.mainSizer.Add(self.displaycanvas, 1, wx.EXPAND|wx.ALL, 5)
self.SetSizerAndFit(self.mainSizer)

This panel is then added to another panel, where its size get's determined relative to other panels that are being added. While I'm happy with the outer size of the panel, I can't get the figure to fit the panel:

enter image description here

The large panel with all the paws should be scaled to fit the panel, while maintaining its aspect ratio.

So I'm wondering, why won't the figure expand to fit the panel?

like image 938
Ivo Flipse Avatar asked Jun 16 '11 15:06

Ivo Flipse


1 Answers

Instead of getting your axes from the add_subplot method, you can create an axes object with explicit boundaries. So instead of

self.axes = self.figure.add_subplot(111)

use

self.axes = self.figure.add_axes([0,0,1,1])

The four numbers are the left edge, bottom edge, width and height of the axes in fractions of figure width and height. [0,0,1,1] will expand the image to fit the entire figure. Of course, there are still issues with the aspect ratio. If you want to maintain the aspect ratio of your image, then it won't always fill the entire widget space (depending on the shape of the widget). If aspect ratio changes are ok, you can call im_show like this

self.axes.imshow(self.data, interpolation="quadric", aspect='auto')

which will make the image fill the widget, no matter what the shape.

Without the automatic aspect ratio this results in:

enter image description here

like image 176
Stephen Terry Avatar answered Oct 20 '22 16:10

Stephen Terry