Figure GUI freezing

后端 未结 2 1607
攒了一身酷
攒了一身酷 2020-12-12 03:35

I am fairly new in python, and I am trying to have a plot, based on data stored in a file. This file may be updated at any time, so I am trying to make the drawing updated e

2条回答
  •  囚心锁ツ
    2020-12-12 04:11

    On top of the answer of @tcaswell (that solve the problem), I suggest to rethink the script in a more OO way.

    I have tried this:

    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)
    

    but it does not work (it looks like it opens a gui at plt.figure and then at each loop.

    A solution like this:

    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)
    

    is much more efficient (axes are created only once), neater (at the end matplotlib is OO) and potentially less prone to memory leaks.

    Besides, from your most I gather that at each loop you read in the files again and then plot the new lines. If this is the case, you want to clear first the content of the axes before redrawing. In my simple case you can clear the axes with

    for a in ax:
        a.clear()
    

提交回复
热议问题