Search code examples
python-2.7matplotlibpsychopy

Matplotlib: Displaying and closing a plot using a loop


Using Matplotlib and a for loop, is it possible to display a plot for a given period of time and then have it close when the for loop is done?

I have tried the following, but the plot simply remains open and the loop doesn't end:

import matplotlib.pyplot as plt
import psychopy

x = [34.00,108.00,64.00,99.00,99.00,51.00]
y = [5.00,17.00,11.00,8.00,14.00,5.00]

scatter(x, y, color = "black")

clock = core.Clock()

while clock.getTime() < 10.0:
    plt.show()

plt.close()

Thanks


Solution

  • You can use interactive mode plt.ion() in combination with plt.pause().

    E.g. to show your window for 5 seconds:

    import matplotlib.pyplot as plt
    
    x = [34.00,108.00,64.00,99.00,99.00,51.00]
    y = [5.00,17.00,11.00,8.00,14.00,5.00]
    
    plt.scatter(x, y, color = "black")
    plt.ion()
    plt.draw()
    plt.pause(5)