matplotlib/matplotlib — Issue #532: Figure.tight_layout() error or doesn't work on Win with wxPython
Author: cmpython
Created: 2011-10-17 03:44:16+00:00
State: open

The tight_layout() method (new in mpl 1.1.0), when used with the OO matplotlib, is either throwing an error ("ValueError: left cannot be >= right") or doesn't do what it is supposed to when used with WinXP. Description, traceback, and sample script below.

This appears to be a platform dependent issue. I have tested this with the following platform/version: WinXP + matplotlib 1.1.0 + wxpython 2.8.10 + Python 2.5 (doesn't work). It has also been tested on Linux + python 2.7.2 + wxgtk 2.8.11.0 + mpl master branch (does work). It would be great if others could test on other platforms and versions, particularly on Windows.

Description: There are two problems. (1) The error occurs if you call .Layout() on the parent of the matplotlib canvas and then call Figure.tight_layout(). If you do not call .Layout() first, you will not get the error. (2) However, even if you don't, the figure's layout is *not* changing to accommodate axis labels--which it should using tight_layout().

The error traceback:

Traceback (most recent call last):
File "C:\Documents and
Settings\user\Desktop\testing_tight_layout.py", line 35, in
frame = Frame1(None)
File "C:\Documents and
Settings\user\Desktop\testing_tight_layout.py", line 14, in __init__
self.Add_MPL_Plot()
File "C:\Documents and
Settings\user\Desktop\testing_tight_layout.py", line 30, in
Add_MPL_Plot
self.figure.tight_layout()
File "C:\Python25\Lib\site-packages\matplotlib\figure.py", line
1393, in tight_layout
self.subplots_adjust(**kwargs)
File "C:\Python25\Lib\site-packages\matplotlib\figure.py", line
1218, in subplots_adjust
self.subplotpars.update(*args, **kwargs)
File "C:\Python25\Lib\site-packages\matplotlib\figure.py", line 183, in update
raise ValueError('left cannot be >= right')
ValueError: left cannot be >= right

Sample script that reproduces the problem:

import wx
import matplotlib
matplotlib.use( 'WXAgg' )
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
from matplotlib.figure import Figure

class Frame1(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self,None)
self.panel = wx.Panel(self)
self.panel.SetBackgroundColour('red')
self.sizer = wx.BoxSizer()
self.panel.SetSizer(self.sizer)
self.Add_MPL_Plot()

def Add_MPL_Plot(self):
self.figure = Figure(None, 80)
self.canvas = FigureCanvasWxAgg(self.panel, -1, self.figure)
self.subplot = self.figure.add_subplot(111)

self.sizer.AddWindow(self.canvas, 1, border=0, flag=wx.EXPAND)
#This line, when not commented out, causes the error
#self.panel.Layout()

self.subplot.plot([1,2,5,3])
self.subplot.set_xlabel('X AXIS LABEL',fontsize=16)
self.subplot.set_ylabel('Y AXIS LABEL',fontsize=16)

#tight_layout here is NOT adjusting the figure
self.figure.tight_layout()

if __name__ == '__main__':
app = wx.PySimpleApp()
frame = Frame1(None)
frame.Show()

app.MainLoop()