Matplotlib动画和Matplotlib小部件之间的冲突?

2024-04-19 09:48:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我用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()

animation

我添加了一个滑块来动态更新动画中圆的直径。现在,这种方法可行,但也有许多明显的缺陷:

  • 当我在滑块上拖动鼠标时,动画会减慢。。。在这个例子中这并不是很糟糕,但是我的(真实的)用例需要在后台进行更繁重的工作。在
  • 初始圆总是出现在图上(右边)。我想删除它,但不知何故ax.clear()没有起作用。在
  • 当我调整窗口大小时,背景变为黑色,如下图所示:

animation black

我不熟悉Matplotlib,所以很可能我做错了。有什么想法吗?在


Tags: importselftimematplotlibdef动画pltval