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()

对于第一个间隔[0,2π],图形不会出现. 有什么错误吗?

推荐答案

我稍微更改了一下您的代码:

  • 首先,我在animate函数外部绘制第一帧,并从它生成一个line对象
  • 然后我更新animate函数中的line个数据
  • 我建议使用i计数器(从0开始,每帧递增1)来更新数据,而不是调用global个变量并更改它们

完整代码

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()

enter image description here

Python相关问答推荐

这些变量是否相等,因为它们引用相同的实例,尽管它们看起来应该具有不同的值?

每个组每第n行就有Pandas

使用Python进行网页抓取,没有页面

如何在telegram 机器人中发送音频?

在Arrow上迭代的快速方法.Julia中包含3000万行和25列的表

如何修复使用turtle和tkinter制作的绘画应用程序的撤销功能

LAB中的增强数组

计算相同形状的两个张量的SSE损失

提取两行之间的标题的常规表达

处理带有间隙(空)的duckDB上的重复副本并有效填充它们

优化pytorch函数以消除for循环

PMMLPipeline._ fit()需要2到3个位置参数,但给出了4个位置参数

我如何使法国在 map 中完全透明的代码?

"使用odbc_connect(raw)连接字符串登录失败;可用于pyodbc"

在单个对象中解析多个Python数据帧

如何在PySide/Qt QColumbnView中删除列

matplotlib + python foor loop

ConversationalRetrivalChain引发键错误

Python避免mypy在相互引用中从另一个类重定义类时失败

关于两个表达式的区别