Why does the plotting function plt.show() behave differently when inside or outside a loop?

Viewed 182

For example, check out the answer to a previous question: here putting plt.show() outside the for loop allows one to plot "live" plots. As if the code is being compiled before execution. While you are in i'th iteration, how does python know to show the plot, when the plt.show() command come after the loop ?

How do I plot in real-time in a while loop using matplotlib?

import numpy as np
import matplotlib.pyplot as plt

plt.axis([0, 10, 0, 1])

for i in range(10):
    y = np.random.random()
    plt.scatter(i, y)
    plt.pause(0.05)

plt.show()
1 Answers

use plt.show(block=False) as below

import numpy as np
import matplotlib.pyplot as plt

plt.axis([0, 10, 0, 1])

for i in range(10):
    y = np.random.random()
    plt.scatter(i, y)
    plt.pause(0.05)
    plt.show(block=False)
Related