sku
sku

Reputation: 137

matplotlib - how to draw a new plot in a loop in the same window

I use the below code. This comes up with three different windows. I would like the plot to show up in the same window. Any ideas?

Thanks

-- ps: clarification. I would like to see the curve of y[0] vs x[0] first then it erased and see y[1] vs x[1] and then it erased and see y[2] vs x[2]. Right now it is showing all three with three different colors. See second chunk of code.

--

import numpy
from matplotlib import pyplot as plt
x = [1, 2, 3]
plt.ion() # turn on interactive mode, non-blocking `show`
for loop in range(0,3):
    y = numpy.dot(x, loop)
    plt.figure()   # create a new figure
    plt.plot(x,y)  # plot the figure
    plt.show()     # show the figure, non-blocking
    _ = input("Press [enter] to continue.") # wait for input from the 



import numpy
import matplotlib.pyplot as plt

%matplotlib notebook

x = [[1, 2, 3], [4,5,6], [7,8,9]]
y = [[1,4,9], [16,25,36], [49,64,81]]

fig, ax = plt.subplots()

plt.ion()
plt.show()
for i in range(3): 
    ax.plot(x[i],y[i])  # plot the figure
    plt.gcf().canvas.draw()
    _ = input("Press [enter] to continue.") # wait for input from the 

Upvotes: 0

Views: 2720

Answers (1)

Sameeresque
Sameeresque

Reputation: 2602

This should help you with the problem. Notice the use of plt.show() outside the loop. plt.show() starts an event loop, checks for the currently active figure objects, and opens a display window.

import numpy
%matplotlib notebook
import matplotlib.pyplot as plt

x = [1, 2, 3]
fig, ax = plt.subplots()

plt.ion()
plt.show()
for loop in range(0,3): 
    y = numpy.dot(x, loop)
    line,=ax.plot(x,y)  # plot the figure
    plt.gcf().canvas.draw()
    line.remove()
    del line
    _ = input("Press [enter] to continue.") # wait for input from the 

Upvotes: 1

Related Questions