[PYTHON] Asynchronously run matplotlib interactive mode

The interactive mode of matplotlib is slow. If you want to visualize the calculation results on a regular basis, you want to avoid blocking the main calculation while drawing.

test.py


import numpy as np
import matplotlib.pyplot as plt
import time
import multiprocessing as mp

class Worker(object):
    def __init__(self, queue):
        self.queue = queue

    def loop(self):
        while True:
            obj = np.random.random((100, 100))
            self.queue.put(obj)
            time.sleep(1)

    def __call__(self):
        self.loop()

queue = mp.Queue()
worker = Worker(queue)
p = mp.Process(target=worker)
p.daemon = True

# initialize plot
plt.ion()
imshow = plt.imshow(np.random.random((100, 100)))
plt.show()

p.start()

while True:
    obj = queue.get()
    imshow.set_data(obj)
    plt.draw()
    plt.pause(0.0001)

Let Worker execute the calculation, and receive the calculation result through Queue and draw it every time the calculation is completed.

Recommended Posts

Asynchronously run matplotlib interactive mode
Extend Python's interactive mode
How to run matplotlib on heroku
Run Matplotlib on a Docker container
run uwsgi server in uwsgi-gevent mode
Until you install and run matplotlib