0
votes

If I run the following code:

import matplotlib.pyplot as plt
import numpy as np

#plt.ion()

while True:
    print('loop')
    x = range(10)
    y = np.random.rand(10)
    plt.scatter(x, y)
    plt.show()

Then I see a scatter plot displayed on my screen. Then each time I close the window for the plot, it displays a new plot with new data.

However, if I uncomment the line plt.ion(), nothing is displayed at all. There is no window created, and the program just continues through the loop, printing out 'loop'.

I want to be able to display a graph, and then return to the code automatically, with the graph still displayed. How can I do this?

1
How do you plan to break out of the infinite while loop? - Sheldore

1 Answers

1
votes

If you want to plot on top of the same figure window, rather than generating a new window at every iteration the following will work:

import matplotlib.pyplot as plt
import numpy as np

plt.ion()

fig, ax = plt.subplots(1, 1)

while True:
    # If wanting to see an "animation" of points added, add a pause to allow the plotting to take place
    plt.pause(1)
    x = range(10)
    y = np.random.rand(10)
    ax.scatter(x, y)

The result you see will depend on the which matplotlib backend you are using. If you're wanting to see the new points being added you should use Qt4 or Qt5