How can I attach a pyplot function to a figure instance?

As a bit of explanation of what is going on here, matplotlib has two semi-independent interfaces; the state machine and the OO interface.

The state machine code is designed for working in an interactive shell (and mimics matlab’s interface). It does this by wrapping the OO interface in a set of commands that keep track of what the current figure and axes are. When you use the command from matplotlib.pyplot (I suspect you have an from matploblib.pyplot import * in your code) in is more or less equivalent to doing gcf().gca().contour(...). When you create a new figure, it is automatically made current (which is what you want if you are using this in an iteractive shell) so the behavior you see is the ‘correct’ behavior. The state machine interface also has code in it to make sure figures get re-drawn when they need to, manage the gui event loops, etc (all the things you need to do to make the interactive interface work smoothly). As hayden mentioned in comments, running ipython --pylab will automatically run from matplotlib.pyplot import *, which gives you a very nice interactive shell.

The OO interface is designed for programmatic dealing with matplotlib. What it adds in verbosity (you now have to do most of the work of the state machine), it makes up for in clarity. In the OO model, most (maybe all) of the plotting functions are associated with Axes objects (doc) (as there can be more than one axes associated with a figure (ex subplots using gridspec).

An alternate way to solve your problem is

ax = fig1.gca()

which will grab the current axes from fig1, creating one if necessary. This may be helpful if you keep track of your figure objects, but not your axes objects and want to add another graph to the figure.

Leave a Comment