为了账号安全,请及时绑定邮箱和手机立即绑定

使用Matplotlib以非阻塞方式绘图

使用Matplotlib以非阻塞方式绘图

慕的地8271018 2019-09-20 16:34:18
在过去的几天里,我一直在玩Numpy和matplotlib。我在尝试使matplotlib绘制函数而不阻塞执行时遇到问题。我知道在这里已经有很多线索提出了类似的问题,而且我已经搜索了很多但是没有设法让这项工作成功。我曾经尝试过使用show(block = False),但我得到的只是一个冻结的窗口。如果我只是调用show(),则会正确绘制结果,但会阻止执行直到窗口关闭。从我读过的其他主题,我怀疑show(block = False)是否有效取决于后端。这个对吗?我的后端是Qt4Agg。你能看看我的代码并告诉我你是否看错了吗?这是我的代码。谢谢你的帮助。from math import *from matplotlib import pyplot as pltprint plt.get_backend()def main():    x = range(-50, 51, 1)    for pow in range(1,5):   # plot x^1, x^2, ..., x^4        y = [Xi**pow for Xi in x]        print y        plt.plot(x, y)        plt.draw()        #plt.show()             #this plots correctly, but blocks execution.        plt.show(block=False)   #this creates an empty frozen window.        _ = raw_input("Press [enter] to continue.")if __name__ == '__main__':    main()PS。我忘了说我想在每次绘制内容时更新现有窗口,而不是创建一个新窗口。
查看完整描述

3 回答

?
翻翻过去那场雪

TA贡献2065条经验 获得超14个赞

您可以通过将绘图写入数组,然后在不同的线程中显示数组来避免阻止执行。以下是使用pyformulas 0.2.8中的 pf.screen同时生成和显示绘图的示例:


import pyformulas as pf

import matplotlib.pyplot as plt

import numpy as np

import time


fig = plt.figure()


canvas = np.zeros((480,640))

screen = pf.screen(canvas, 'Sinusoid')


start = time.time()

while True:

    now = time.time() - start


    x = np.linspace(now-2, now, 100)

    y = np.sin(2*np.pi*x) + np.sin(3*np.pi*x)

    plt.xlim(now-2,now+1)

    plt.ylim(-3,3)

    plt.plot(x, y, c='black')


    # If we haven't already shown or saved the plot, then we need to draw the figure first...

    fig.canvas.draw()


    image = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')

    image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,))


    screen.update(image)


#screen.close()

结果:

//img1.sycdn.imooc.com//5d848f3d000138c505080324.jpg

查看完整回答
反对 回复 2019-09-20
  • 3 回答
  • 0 关注
  • 2594 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信