Python 如何在Matplotlib中沿线程执行动画?

Python 如何在Matplotlib中沿线程执行动画?,python,multithreading,matplotlib,animation,Python,Multithreading,Matplotlib,Animation,我想通过线程每0.25秒更改一次圆圈颜色,并通过matplotlib动画实时显示结果。这是我的代码(我甚至不明白为什么不执行动画): 这里的问题是什么?如何解决?如果要每0.25秒更改一次颜色,则应为动画的间隔: import matplotlib.pyplot as plt from matplotlib.patches import Circle from matplotlib.animation import FuncAnimation fig, ax = plt.subplots()

我想通过线程每0.25秒更改一次圆圈颜色,并通过
matplotlib
动画实时显示结果。这是我的代码(我甚至不明白为什么不执行动画):


这里的问题是什么?如何解决?

如果要每0.25秒更改一次颜色,则应为动画的间隔:

import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
ax.axis('square')

c = Circle(xy = (0, 0), color = "red")
ax.add_patch(c)
ax.set_xlim([-50, 50])
ax.set_ylim([-50, 50])

def change_color(i):
    c.set_fc((i/100, 0, 0, 1))

ani = FuncAnimation(fig, change_color, frames = range(100), interval=250)

plt.show()

你是在交互模式下运行这个吗?在这种情况下,问题是由于
plt.show()
没有阻塞,函数返回,并且没有对
FuncAnimation
的引用,因此它被垃圾收集。在交互模式之外,代码本身运行良好。但不确定线程的用途。@重要的是FBeingernest尝试过不使用线程,只使用动画,问题是它的线程速度很慢。我试过了。但是为什么它很慢呢?(不平稳)速度由
间隔决定。据我所知,您希望它每四分之一秒(=250毫秒)发生变化;当然,你可以设置一个较低的间隔来让动画更平滑地运行。问题还在于,如果我设置
interval=0.5
etc(小于1),那么动画什么都不做。我认为使用
Thread
将有助于使动画平滑。你不能低于1毫秒的间隔。
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
ax.axis('square')

c = Circle(xy = (0, 0), color = "red")
ax.add_patch(c)
ax.set_xlim([-50, 50])
ax.set_ylim([-50, 50])

def change_color(i):
    c.set_fc((i/100, 0, 0, 1))

ani = FuncAnimation(fig, change_color, frames = range(100), interval=250)

plt.show()