LoginSignup
4
3

More than 5 years have passed since last update.

matplotlibのinteractive modeを非同期で実行する

Last updated at Posted at 2017-08-12

matplotlibのinteractive modeは遅い.定期的に計算結果を可視化するような場合,描画をする間にメインの計算がブロックされてしまうのを避けたい.

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)

Workerに計算を実行させて,計算が終わる度にQueueを通して計算結果を受け取って描画する.

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3