Home > OS >  Continously refreshing a matplotlib figure results in a slowdown
Continously refreshing a matplotlib figure results in a slowdown

Time:04-13

I have the following code that displays a figure with two images:

import numpy as np
import matplotlib.pyplot as plt

img1 = np.zeros((400,400,3), dtype=np.uint8)
img2 = np.ones((400,400,3), dtype=np.uint8) * 255

f, axarr = plt.subplots(1,2)

counter = 0
while True:
    print('Counter=', counter)
    counter  = 1
    axarr[0].imshow(img1)
    axarr[1].imshow(img2)
    plt.draw()
    plt.pause(0.01)

The images are going to be regenerated at each iteration, and I want to continuously refresh the figure. The code works, but at each iteration it is slower and slower. I suspect there is some kind of leak, or at least something that I'm doing wrong.

But what?

Shall I call clf()? I tried, and it creates a new window at each iteration. Shall I call

fig = plt.figure()

and somehow release the newly created figure at each iteration? (but how, in this case?)

CodePudding user response:

Every time you call axarr[0].imshow(img1), a new image will be added to the axes. Try to clear at each iteration the images stored with axarr[0].images = [] and axarr[1].images = [] (or axarr[0].images.clear() and axarr[1].images.clear()).

  • Related