Python realtime plotting

后端 未结 4 1619
感动是毒
感动是毒 2020-12-09 13:42

I acquire some data in two arrays: one for the time, and one for the value. When I reach 1000 points, I trigger a signal and plot these points (x=time, y=value).

I n

4条回答
  •  执念已碎
    2020-12-09 14:24

    The lightest solution you may have is to replace the X and Y values of an existing plot. (Or the Y value only, if your X data does not change. A simple example:

    import matplotlib.pyplot as plt
    import numpy as np
    import time
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    # some X and Y data
    x = np.arange(10000)
    y = np.random.randn(10000)
    
    li, = ax.plot(x, y)
    
    # draw and show it
    ax.relim() 
    ax.autoscale_view(True,True,True)
    fig.canvas.draw()
    plt.show(block=False)
    
    # loop to update the data
    while True:
        try:
            y[:-10] = y[10:]
            y[-10:] = np.random.randn(10)
    
            # set the new data
            li.set_ydata(y)
    
            fig.canvas.draw()
    
            time.sleep(0.01)
        except KeyboardInterrupt:
            break
    

    This solution is quite fast, as well. The maximum speed of the above code is 100 redraws per second (limited by the time.sleep), I get around 70-80, which means that one redraw takes around 4 ms. But YMMV depending on the backend, etc.

提交回复
热议问题