Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

python matplotlib: plotting in another process

EDIT: The ultimate requirement for such a Python program is: Receive data from UART from a external circuitry (which probably is equipped with some sensors), the program will process these data, and draw a dynamically updated curve on the computer screen.

So, I want to plot dynamically, the following test script starts a sub-process, and in that process, it accepts data from parent process through a Queue, and plot data accordingly.

But when the script is run, only an empty figure is shown, I can see the console prints "put:" and "got:" messages, meaning both parent and subprocess are running and communicating, but nothing happens in the GUI figure window.

Furthermore, the GUI window is not responsive and if I click on the window, it will crash.

The system is Windows 10, 64 bit. Python version is 2.7 (32bit)

What's the problem here? thank you!

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

def worker(q):
    plt.ion()
    ln, = plt.plot([], [])
    plt.show()

    while True:
        obj = q.get()
        n = obj + 0
        print "sub : got:", n

        ln.set_xdata(numpy.append(ln.get_xdata(), n))
        ln.set_ydata(numpy.append(ln.get_ydata(), n))
        plt.draw()

if __name__ == '__main__':
    queue = mp.Queue()
    p = mp.Process(target=worker, args=(queue,))
    p.start()

    while True:
        n = random.random() * 5
        print "main: put:", n
        queue.put(n)
        time.sleep(1.0)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to rescale, otherwise nothing will appear:

This works on my computer :

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

def worker(q):
    #plt.ion()
    fig=plt.figure()
    ax=fig.add_subplot(111)
    ln, = ax.plot([], [])
    fig.canvas.draw()   # draw and show it
    plt.show(block=False)

    while True:
        obj = q.get()
        n = obj + 0
        print "sub : got:", n

        ln.set_xdata(numpy.append(ln.get_xdata(), n))
        ln.set_ydata(numpy.append(ln.get_ydata(), n))
        ax.relim()

        ax.autoscale_view(True,True,True)
        fig.canvas.draw()

if __name__ == '__main__':
    queue = mp.Queue()
    p = mp.Process(target=worker, args=(queue,))
    p.start()

    while True:
        n = random.random() * 5
        print "main: put:", n
        queue.put(n)
        time.sleep(1.0)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...