Dynamically updating a bar plot in matplotlib

前端 未结 2 599
梦如初夏
梦如初夏 2020-12-03 08:45

I have a number of sensors attached to my Raspberry Pi; I\'m sending their data to my PC twice a second using TCP. I would like to continuously graph these values using matp

2条回答
  •  感动是毒
    2020-12-03 09:24

    You could use animation.FuncAnimation. Plot the bar plot once and save the return value, which is a collection of Rects:

    rects = plt.bar(range(N), x, align='center')
    

    Then, to change the height of a bar, call rect.set_height:

        for rect, h in zip(rects, x):
            rect.set_height(h)
    

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation
    
    def animate(frameno):
        x = mu + sigma * np.random.randn(N)
        n, _ = np.histogram(x, bins, normed=True)
        for rect, h in zip(patches, n):
            rect.set_height(h)
        return patches
    
    N, mu, sigma = 10000, 100, 15
    fig, ax = plt.subplots()
    x = mu + sigma * np.random.randn(N)
    n, bins, patches = plt.hist(x, 50, normed=1, facecolor='green', alpha=0.75)
    
    frames = 100
    ani = animation.FuncAnimation(fig, animate, blit=True, interval=0,
                                  frames=frames,
                                  repeat=False)
    plt.show()
    

提交回复
热议问题