I have the following code which creates a graph animation. The graph should start from 0, but the 1st interval graph isn't coming.
Below is the code:
import matplotlib.pylab as plt
import matplotlib.animation as animation
import numpy as np
fig, ax = plt.subplots()
left = -1
right = 2*np.pi - 1
def animate(i):
global left, right
left = left 1
right = right 1
x = np.linspace(left, right, 50)
y = np.cos(x)
ax.cla()
ax.set_xlim(left, right)
ax.plot(x, y, lw=2)
ani = animation.FuncAnimation(fig, animate, interval = 1000)
plt.show()
For the 1st interval [0, 2π] the graph isn't coming. What's the mistake?
CodePudding user response:
I changed a little bit your code:
- first of all I plot the first frame outside the
animatefunction and I generate alineobject from it - then I update the
linedata withinanimatefunction - I suggest to use
icounter (which starts from0and increases by1in each frame) to update your data, in place of callingglobalvariables and change them
Complete Code
import matplotlib.pylab as plt
import matplotlib.animation as animation
import numpy as np
fig, ax = plt.subplots()
left = 0
right = 2*np.pi
x = np.linspace(left, right, 50)
y = np.cos(x)
line, = ax.plot(x, y)
ax.set_xlim(left, right)
def animate(i):
x = np.linspace(left i, right i, 50)
y = np.cos(x)
line.set_data(x, y)
ax.set_xlim(left i, right i)
return line,
ani = animation.FuncAnimation(fig = fig, func = animate, interval = 1000)
plt.show()

