gpt4 book ai didi

python - 在 python/matplotlib 中动画补丁对象

转载 作者:太空狗 更新时间:2023-10-30 02:46:33 25 4
gpt4 key购买 nike

我正在尝试为一组圆圈制作动画,以便它们随时间改变颜色。下面的代码生成了一个单帧的例子:

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

nx = 20
ny = 20

fig = plt.figure()
plt.axis([0,nx,0,ny])
ax = plt.gca()
ax.set_aspect(1)

for x in range(0,nx):
for y in range(0,ny):
ax.add_patch( plt.Circle((x+0.5,y+0.5),0.45,color='r') )

plt.show()

如何定义函数 init() 和 animate() 以便我可以使用以下方法制作动画:

animation.FuncAnimation(fig, animate, initfunc=init,interval=200, blit=True)

最佳答案

您可以像这样更改动画中圆圈的颜色:

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

nx = 20
ny = 20

fig = plt.figure()
plt.axis([0,nx,0,ny])
ax = plt.gca()
ax.set_aspect(1)

def init():
# initialize an empty list of cirlces
return []

def animate(i):
# draw circles, select to color for the circles based on the input argument i.
someColors = ['r', 'b', 'g', 'm', 'y']
patches = []
for x in range(0,nx):
for y in range(0,ny):
patches.append(ax.add_patch( plt.Circle((x+0.5,y+0.5),0.45,color=someColors[i % 5]) ))
return patches

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

关于python - 在 python/matplotlib 中动画补丁对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19981054/

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