Reputation: 567
I'm looking for a simple timed animation example for matplotlib. I've found several references to the subplot example in the matplotlib library but I need to see something much more basic on which to model my code.
I have 10 discrete values on the x axis, and a continuous value on the y axis (think histogram). The relationships between x and y change over 500 timesteps.
Here's a ridiculously truncated version of a dataset with just 5 categories and 5 timesteps:
x = list(range(0, 5))
y = [[2.00000000e-01, 2.00000000e-01, 2.75495888e-02,
1.40100625e-02, 2.00000000e-01], [1.40100625e-02,
3.85989938e-01, 6.20454173e-03, 1.74945474e-03,
2.00000000e-01], [1.74945474e-03, 3.98250545e-01,
1.24956950e-03, 2.30229281e-04, 2.00000000e-01],
[2.30229281e-04, 3.99769771e-01, 2.26476892e-04,
3.05018276e-05, 2.00000000e-01], [3.05018276e-05,
3.99969498e-01, 3.82455658e-05, 4.04459287e-06,
2.00000000e-01]]
How would one animate such a dataset in matplotlib?
Upvotes: 0
Views: 3197
Reputation: 339765
Here is the example from this question's answer, using the data from above.
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
x = list(range(0, 5))
y = [[2.00000000e-01, 2.00000000e-01, 2.75495888e-02,
1.40100625e-02, 2.00000000e-01], [1.40100625e-02,
3.85989938e-01, 6.20454173e-03, 1.74945474e-03,
2.00000000e-01], [1.74945474e-03, 3.98250545e-01,
1.24956950e-03, 2.30229281e-04, 2.00000000e-01],
[2.30229281e-04, 3.99769771e-01, 2.26476892e-04,
3.05018276e-05, 2.00000000e-01], [3.05018276e-05,
3.99969498e-01, 3.82455658e-05, 4.04459287e-06,
2.00000000e-01]]
fig, ax = plt.subplots()
sc = ax.scatter(x,y[0])
plt.ylim(-0.1,0.5)
def animate(i):
sc.set_offsets(np.c_[x,y[i]])
ani = matplotlib.animation.FuncAnimation(fig, animate,
frames=len(y), interval=300, repeat=True)
plt.show()
Upvotes: 1