我使用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 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的新手,所以很可能我做错了。有什么想法吗?