使用Matplotlib以非阻塞方式绘图

在过去的几天里,我一直在玩Numpy和matplotlib。我在尝试使matplotlib绘制函数而不阻塞执行时遇到问题。我知道在这里已经有很多线索提出了类似的问题,而且我已经搜索了很多但是没有设法让这项工作成功。


我曾经尝试过使用show(block = False),但我得到的只是一个冻结的窗口。如果我只是调用show(),则会正确绘制结果,但会阻止执行直到窗口关闭。从我读过的其他主题,我怀疑show(block = False)是否有效取决于后端。这个对吗?我的后端是Qt4Agg。你能看看我的代码并告诉我你是否看错了吗?这是我的代码。谢谢你的帮助。


from math import *

from matplotlib import pyplot as plt

print 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。我忘了说我想在每次绘制内容时更新现有窗口,而不是创建一个新窗口。


慕的地8271018
浏览 2595回答 3
3回答

翻翻过去那场雪

您可以通过将绘图写入数组,然后在不同的线程中显示数组来避免阻止执行。以下是使用pyformulas 0.2.8中的 pf.screen同时生成和显示绘图的示例:import pyformulas as pfimport matplotlib.pyplot as pltimport numpy as npimport timefig = 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()结果:
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python