图GUI冻结

时间:2013-02-01 13:35:24

标签: python matplotlib plot freeze subplot

我在python中相当新,我正在尝试根据存储在文件中的数据绘制一个图表。此文件可能随时更新,因此我尝试每3秒更新一次图形(因此我不使用所有CPU)。我的问题是午餐后GUI会冻结。

#!/usr/bin/python
# _*_ coding: utf8 _*_

import matplotlib.pyplot as plt
import numpy as np
import time 

plt.ion()
plt.figure()
i=0
while 1:
    taille=0
    fichier=np.loadtxt('data/US.SAVE')
    fichier1=np.loadtxt('data/cond.SAVE')
    taille1=np.size(fichier1[:,1])
    taille=np.size(fichier[:,1])

    min=min(fichier[0,0],fichier1[0,0]);

    fichier[:,0]=fichier[:,0]-min
    fichier1[:,0]=fichier1[:,0]-min


    if (taille != taille1) :
        printErrors("TAILLE DE FICHIERS DIFFERENTES")


    nb_chunks=np.size(fichier1[1,:])
    nb_inputs=np.size(fichier[1,:])


    plt.subplot(3,1,1)

    plt.bar(fichier[:,0],fichier[:,1],align='center',width=0.0001, facecolor='b', label="US")
    x1,x2,y1,y2 = plt.axis()
    x1=x1-0.0001
    plt.axis([x1, x2, y1, 1.2])
    plt.legend(ncol=3,prop={'size':9})
    plt.title("US ") 
    plt.ylabel('Activation')
    plt.xlabel('Time')

    plt.subplot(3,1,2)

    plt.bar(fichier1[:,0],fichier1[:,1],align='center',width=0.0001, facecolor='b', label="response")



    plt.axis([x1, x2, y1, 1.2])
    plt.legend(ncol=3,prop={'size':9})
    plt.title("Response ") 
    plt.ylabel('Activation')
    plt.xlabel('Time')


    plt.subplot(3,1,3)

    plt.bar(fichier[:,0]-fichier1[:,0],fichier1[:,1],align='center',width=0.0001, facecolor='b', label="Error")
    plt.axis([x1, x2, y1, 1.2])
    plt.legend(ncol=3,prop={'size':9})
    plt.title("Error") 
    plt.ylabel('Activation')
    plt.xlabel('Time')
    plt.draw()
    name1='data/Conditionnement.eps'
    plt.savefig(name1,dpi=256)
    plt.draw()
    del fichier,fichier1,min
    i=i+1

    time.sleep(3)   

plt.show()

我没有在基于文件的绘图上找到任何其他主题。

2 个答案:

答案 0 :(得分:2)

您想使用plt.pause(3)功能代替time.sleep()pause包括对gui主循环的必要调用,以使图形重新绘制。

另见:Python- 1 second plots continous presentationmatplotlib real-time linear linepylab.ion() in python 2, matplotlib 1.1.1 and updating of the plot while the program runs

答案 1 :(得分:2)

除了@tcaswell(解决问题)的答案之外,我建议以更多的方式重新考虑脚本。

我试过这个:

plt.ion()
plt.figure()
plt.show()

while True:
    x=np.arange(10)
    y=np.random.rand(10)

    plt.subplot(121)
    plt.plot(x,y)
    plt.subplot(122)        
    plt.plot(x,2*y)

    plt.draw()

    plt.pause(3)

但它不起作用(看起来它在plt.figure然后在每个循环打开一个gui。

这样的解决方案:

plt.ion()
fig, ax = plt.subplots(nrows=2, ncols=1)
plt.show()

while True:
    x=np.arange(10)
    y=np.random.rand(10)

    ax[0].plot(x,y)
    ax[1].plot(x,2*y)

    plt.draw()

    plt.pause(3)

效率更高(轴只创建一次),更整洁(最后matplotlib是OO)并且可能不太容易发生内存泄漏。

此外,从大多数情况来说,我收集的是你在每个循环中再次阅读文件然后绘制新行。如果是这种情况,您需要在重绘之前首先清除轴的内容。在我的简单案例中,您可以使用

清除轴
for a in ax:
    a.clear()
相关问题