1

我是 matplotlib 的新手,正在尝试动画。从 youtube 上观看了一些教程并在下面创建了代码,这几乎是从其中一个教程中复制/粘贴的。我期待绘图会不断更新新的数据点,但它没有发生。我添加了用于故障排除的打印语句,并看到 xcord 和 ycord 只打印了一次——这意味着似乎根本没有调用 animate 函数。请帮助找出我做错了什么。我在 Spyder 4.1.5 中运行此代码

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from itertools import count
import random

xcord = []
ycord = [5]

index = count()
xcord.append(next(index))

def animate(i):
    xcord.append(next(index))
    ycord.append(random.randint(0,5))
    print(xcord)
    print(ycord)
    plt.cla()
    plt.plot(xcord,ycord) 
 
fig, ax = plt.subplots(1,1)
print(xcord)
print(ycord)
ani = FuncAnimation(fig,animate,interval=1000)
plt.tight_layout()
plt.show()
4

1 回答 1

0

我将通过修改官方动画以适合您的代码来回答。线条颜色为红色,线条宽度设置为 3。没有理由指定帧数并关闭重复。您可以根据需要自定义其余部分。

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from itertools import count
import random

xcord = []
ycord = [5]

index = count()
xcord.append(next(index))

fig, ax = plt.subplots(1,1)
ax.set(xlim=(0,20), ylim=(0, 5))
line, = ax.plot([], [], 'r-', lw=3)

def animate(i):
    xcord.append(next(index))
    ycord.append(random.randint(0,5))
    line.set_data(xcord, ycord)

ani = FuncAnimation(fig, animate, frames=19, interval=200, repeat=False)

plt.show()

在此处输入图像描述

于 2021-09-26T02:00:54.833 回答