python matplotlib:在另一个进程中绘图 [英] python matplotlib: plotting in another process

查看:100
本文介绍了python matplotlib:在另一个进程中绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此类Python程序的最终要求是:从外部电路(可能装有一些传感器)从UART接收数据,该程序将处理这些数据,并在计算机屏幕上绘制动态更新的曲线

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.

因此,我想动态绘制,下面的测试脚本启动一个子流程,在该流程中,它通过Queue接受来自父流程的数据,并相应地绘制数据.

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.

但是运行脚本时,只显示一个空的数字,我可以看到控制台显示"put:"和"got:"消息,这意味着父进程和子进程都在运行和通信,但是GUI中什么也没发生图窗口.

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.

此外,GUI窗口没有响应,如果我单击该窗口,它将崩溃.

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

系统是Windows 10(64位). Python版本是2.7(32位)

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

这是什么问题?谢谢!

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)

推荐答案

您必须重新缩放,否则将不会显示任何内容:

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)

这篇关于python matplotlib:在另一个进程中绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆