How to make an animated Matplotlib script?

I'm trying to animate a violin poster, so I started with what I think should be very simple, but it doesn't work. I think the problem is that the script is not accepting set_data, but I don't know how to pass the changing data to the script. For this example, I need a graph where the average is slowly shifting towards higher values. If I am barking the wrong tree, please provide the code that works for animating the violin.

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


fig, ax = plt.subplots()
data = np.random.rand(100)

def animate(i):
    v.set_data(data+i)  # update the data
    return v

v = ax.violinplot([])
ax.set_ylim(0,200)

v_ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), 
                              interval=50, blit=True)

      

+3


source to share


1 answer


Indeed, there is no set_data method for scripting. This is probably because there is a lot of computation going on in the background when creating such a plot, and it is composed of many different elements that are difficult to update.

The easiest option is to just redraw the violin graph and not use blitting.



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


fig, ax = plt.subplots()
data = np.random.normal(loc=25, scale=20, size=100)

def animate(i, data):
    ax.clear()
    ax.set_xlim(0,2)
    ax.set_ylim(0,200)
    data[:20] = np.random.normal(loc=25+i, scale=20, size=20)
    np.random.shuffle(data)
    ax.violinplot(data)

animate(0)

v_ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), 
                              fargs=(data,), interval=50, blit=False)

plt.show()

      

enter image description here

+2


source







All Articles