0

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 
2
  • First, you can add the keywor argument block=False in plt.show(). Second, you are creating a new figure every time you call plt.figure(). To add a new plot just use plt.plot() without refering to the figure. I am not sure about the input(), but it is worth considering matplotlib events or widgets for triggering the plot update, as they still work with plt.show(). Lastly, to update the figure you can call plt.gcf().canvas.draw(). Commented Jun 20, 2020 at 23:10
  • Tried it. Doesn’t work. Shows three different figures. Commented Jun 20, 2020 at 23:22

1 Answer 1

1

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 
Sign up to request clarification or add additional context in comments.

4 Comments

Are you doing it in a Jupyter notebook?
Use %matplotlib notebook.
Thank you. In the question, I have added new code for clarification. I am looking for three separate graphs but this shows three graphs in one window in three colors.
You can delete the line by first defining it, and then invoking line.remove()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.