Search code examples
pythonmatlabnumpymatplotlibplot

Can I have multiple plot windows in interactive mode?


I've been using Matlab/octave for a long time, and I'm transiting to NumPy/SciPy. I find that matplotlib is very similar to figure drawing in Matlab, and it is easy to use.

But, one thing I feel uncomfortable with matplotlib is when I draw a figure using plt.show(), then the process is stuck there, so I cannot type any new commands nor launch another window to draw another figure before closing that window. For example, if we type the following code, then before closing this window, we cannot type any new command nor launch another window for another plot.

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()

This behavior is very different from Matlab plot. We may have multiple figure windows in the Matlab interactive mode.

Can we do the same thing in python interactive mode?


Solution

  • In IPython running %matplotlib enables matplotlib interactive support without importing anything into the interactive namespace. Then running plt.figure() immediately opens a new plot window, plt.imshow() populates it with an image and plt.plot() does the same for tabular data, all without blocking console interactivity.

    With matplotlib interactive mode enabled its ok to run plt.show() and it won't block anything even without setting block=False, which causes IPython to hang fatally in noninteractive mode.

    %pylab also enables matplotlib interactive support, but it loads too many imports and is not recommended.

    External scripts executed with '%run -i' run in IPython's namespace and will have interactive plotting support if its been enabled there.

    For more information on matplotlib interactive mode see What is interactive mode? and Plotting with mathplotlib in IPython.