Python Matplotlib动画和Matplotlib小部件之间存在冲突?
我用Matplotlib创建了一个非常简单的圆动画:Python Matplotlib动画和Matplotlib小部件之间存在冲突?,python,animation,matplotlib,Python,Animation,Matplotlib,我用Matplotlib创建了一个非常简单的圆动画: from numpy import sin, cos, pi import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib.widgets import Slider class MyCircle: def __init__(self): self.diameter = 0.5 def se
from numpy import sin, cos, pi
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.widgets import Slider
class MyCircle:
def __init__(self):
self.diameter = 0.5
def set_diameter(self,val):
self.diameter = val
def get_shape(self,time):
return plt.Circle((cos(time),sin(time)), self.diameter+0.3*sin(time))
circle = MyCircle()
# Figure
fig = plt.figure()
ax = fig.add_subplot(111, autoscale_on=False, xlim=(-2, 2), ylim=(-2, 2))
plt.subplots_adjust(bottom=0.2)
# Slider
ax_diam = plt.axes([0.2, 0.1, 0.65, 0.03], axisbg='lightgoldenrodyellow')
sl_diam = Slider(ax_diam, 'Diameter', 0.1, 2, valinit=circle.diameter)
sl_diam.on_changed(lambda val: circle.set_diameter(val))
# Animation
def animate(i):
shape = circle.get_shape(i*2*pi/100)
ax.clear()
ax.add_patch(shape)
return [shape]
anim = animation.FuncAnimation(fig, animate, frames=100, interval=25, blit=True)
plt.show()
我添加了一个滑块,以便在动画期间动态更新圆的直径。现在,这是可行的,但有各种明显的缺陷:
- 当我在滑块上拖动鼠标时,动画会变慢。。。在这个例子中这并不是那么糟糕,但是我的(真实的)用例需要在后台进行更繁重的工作
- 初始圆始终显示在绘图上(右侧)。我想删除它,但不知何故,
无法完成此任务ax.clear()
- 调整窗口大小时,背景变为黑色,如下图所示:
我是Matplotlib的新手,所以很可能我做错了。有什么想法吗?这不是一个完整的答案,但简而言之,您需要从
函数动画中删除blit=True
。你可以使用blitting,但是你需要手动处理。谢谢@JoeKington,我认为它几乎解决了这三个问题。(不确定动画是否没有变慢,但感觉更平滑)这不是一个完整的答案,但简而言之,您需要从FuncAnimation
中删除blit=True
。你可以使用blitting,但是你需要手动处理。谢谢@JoeKington,我认为它几乎解决了这三个问题。(不确定动画是否完全没有变慢,但感觉更平滑)