Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib pyplot show() doesn't work once closed

I have a loop like this

#!/usr/bin/env python
import matplotlib.pyplot as p

for i in xrange(N):
    # Create my_image here

    # Display this image
    p.figure()
    p.imshow(my_image)
    p.show()
    p.close()

This works fine when i=0. For the program to continue, I need to close the new figure created by pyplot. For all other loop iterations (i>0), another new figure is not created, a plot is not presented and the program just moves on. Why does closing a figure making pyplot unable to open new one (like MATLAB)?

The behavior which I expect is:

  1. Execution stops at p.show()
  2. When I close the figure, execution continues
  3. When p.show() is encountered again, the new image is displayed.
  4. Repeat step 2 until no more plot to show
like image 386
Dat Chu Avatar asked Mar 01 '11 18:03

Dat Chu


People also ask

Is PLT show () necessary?

draw() . Using plt. show() in Matplotlib mode is not required.

What happens if I dont use %Matplotlib inline?

The only reason %matplotlib inline is used is to render any matplotlib diagrams even if the plt. show() function is not called. However, even if %matplotlib inline is not used, Jupyter will still display the Matplotlib diagram as an object, with something like matplotlib. lines.

Does matplotlib work in idle?

Download the “Install Matplotlib (for PC). bat” file from my web site, and double-click it to run it. Test your installation. Start IDLE (Python 3.4 GUI – 32 bit), type “import matplotlib”, and confirm that this command completes without an error.


1 Answers

There might be a better way to animate imshow's, but this should work in a pinch. It's a lightly modified version of an animation example from the docs.

# For detailed comments on animation and the techniqes used here, see
# the wiki entry http://www.scipy.org/Cookbook/Matplotlib/Animations

import matplotlib
matplotlib.use('TkAgg')

import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.cm as cm

import sys
import numpy as np
import time

ax = plt.subplot(111)
canvas = ax.figure.canvas

delta=0.025
x=y= np.arange(-3.0, 3.0, delta)
x,y=np.meshgrid(x, y)
z1=mlab.bivariate_normal(x, y, 1.0, 1.0, 0.0, 0.0)
z2=mlab.bivariate_normal(x, y, 1.5, 0.5, 1, 1)
z=z2-z1  # difference of Gaussians

def run(z):
    fig=plt.gcf()
    for i in range(10):
        plt.imshow(z, interpolation='bilinear', cmap=cm.gray,
                  origin='lower', extent=[-3,3,-3,3])
        canvas.draw()
        plt.clf()
        z**=2

manager = plt.get_current_fig_manager()
manager.window.after(100, run, z)
plt.show()
like image 126
unutbu Avatar answered Sep 28 '22 10:09

unutbu