gpt4 book ai didi

python - 在数组中定义多个绘图对象并在 matplotlib 动画中更新

转载 作者:太空宇宙 更新时间:2023-11-03 14:56:37 24 4
gpt4 key购买 nike

我遵循了以下问题的答案

Defining multiple plots to be animated with a for loop in matplotlib

答案定义并绘制线条,但我想绘制并更新动画中的点。我修改了代码并尝试绘制这些点。当我运行代码时,它显示空白图形,没有绘制任何内容。

from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np

fig = plt.figure()

ax = plt.axes(xlim=(-10, 10), ylim=(0, 100))

N = 4
points = ax.plot( *([[], []]*N) )

def init():
for line in points:
line.set_data([], [])
return points

def animate(i):
# for j,line in enumerate(lines):
# print j,i
# line.set_data([0,j], [2,i])
points[0].set_data([[0],[i]])
points[1].set_data([[1],[i+1]])
points[2].set_data([[2],[i+2]])
points[3].set_data([[3],[i+3]])
return points

anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=100, interval=20, blit=True)

plt.show()

我该如何解决这个问题?

谢谢

最佳答案

set_data()函数在绘制一条线时需要至少包含 2 个元素的列表。

例如:

def animate(i):
points[0].set_data([[0, 1],[i, i+1]])
points[1].set_data([[1, 2],[i+1, i+2]])
points[2].set_data([[2, 3],[i+2, i+3]])
points[3].set_data([[3, 4],[i+3, i+4]])
return points

只需使点可见,因为我们放置了一个标记:

points = ax.plot( *([[], []]*N), marker="o")

完整代码:

fig = plt.figure()

ax = plt.axes(xlim=(-10, 10), ylim=(0, 100))

N = 4
points = ax.plot( *([[], []]*N), marker="o")

def init():
for line in points:
line.set_data([], [])
return points

def animate(i):
points[0].set_data([0],[i])
points[1].set_data([[1],[i+1]])
points[2].set_data([[2],[i+2]])
points[3].set_data([[3],[i+3]])
return points

anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=100, interval=20, blit=True)

plt.show()

enter image description here

关于python - 在数组中定义多个绘图对象并在 matplotlib 动画中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45515563/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com