简体   繁体   中英

Matplotlib FuncAnimation 1st interval of graph not coming

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?

I changed a little bit your code:

  • first of all I plot the first frame outside the animate function and I generate a line object from it
  • then I update the line data within animate function
  • I suggest to use i counter (which starts from 0 and increases by 1 in each frame) to update your data, in place of calling global variables 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()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM