Skip to content
Advertisement

Multiple (matplotlib) plots generated in loop not visibly updating

So I’m trying to generate two separate figures in a loop, such that on each iteration the plots are refreshed with the most recent output of a function:

import numpy as np
from matplotlib import pyplot as plt

figA, axA = plt.subplots()
figB, axB = plt.subplots()

for n in range(10):
    dataA = np.random.randint(0, 10, 10)
    dataB = np.random.randint(0, 10, 10)

    axA.clear()
    axB.clear()

    axA.plot(dataA)
    axB.plot(dataB)

    plt.show()
    plt.pause(1)

However what’s happening is that only figB is visibly updated, while figA is not. Once the loop completes, then both plots display the final output.

Why are both figures not visibly updating on each loop?

(edit: runnable code, addition of plt.show(), though this does not solve the issue)

Advertisement

Answer

Found a solution — I replaced the plt.show() with figA.canvas.draw() and figB.canvas.draw(), which refreshes both plots on every loop.

Still not sure I understand what or why that works instead. The matplotlib functions seem needlessly opaque and disparate to do what ought to be simple plotting tasks.

Advertisement