Python FuncAnimation帧覆盖时,滑块添加到figu

2024-05-14 06:43:45 发布

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

我有一个三维散点图的动画。动画是用 FuncAnimation来自matplotlib.animation。一切正常,直到我添加一个滑块到数字。然后动画中的帧仍然存在,我看到在旧帧上绘制的每个新帧(见附图)。我不太清楚FuncAnimation是如何工作的(反复试验),所以,我不知道突然出了什么问题。在

下面是我如何运行动画的详细说明。在


动画在我命名为MyAnim的类中处理,当类初始化时,我首先使用以下方法创建3D图形:

class MyAnim(object):
    """Animates points on 3D wireplot"""

    def __init__(self, [...]):

        [...]

        self.fig = plt.figure(figsize = (8,8))            
        self.subplot = self.fig.add_subplot(111, projection='3d')
        self.subplot._axis3don = False  

然后我运行anim方法,启动动画循环:

^{pr2}$

self.init中,我初始化一个虚拟散点图(单个透明(alpha = 0)点为零)。在

def init(self):    
   """Animation initialization"""

   self.subplot_3d_wires = self.subplot.scatter([0], [0], [0], c = RED, s = 100, alpha = 0)
   return [self.subplot_3d_wires]

动画本身包括重新评估线图next_pos的网格点的位置,以及红色(x_red, y_red, z_red)和蓝色(x_blue, y_blue, z_blue)散射点的新位置,然后绘制在导线图的顶部。在

所以这两个部分的情节是:

def animate3d(self, i):

    plt.cla() 

    [...]

    next_pos = get_next_pos(i)

    [...]

    for j in range(X_SIZE ** 2):            

        step_l = (j) * Z_SIZE
        step_r = (j + 1) * Z_SIZE
        self.subplot_3d_wires = self.subplot.plot_wireframe(next_pos[step_l:step_r, 0], 
                                                            next_pos[step_l:step_r, 1], 
                                                            next_pos[step_l:step_r, 2], 
                                                            rstride = 1, 
                                                            cstride = 1, 
                                                            alpha = 0.2, 
                                                            antialiased = True)

    [...]
    (x_red, y_red, z_red) = get_new_red(i)
    (x_blue, y_blue, z_blue) = get_new_blue(i)

    self.subplot_3d_wires = self.subplot.scatter(x_red, y_red, z_red, s = 150, c = RED,  depthshade = False, lw = 0, alpha = 1)
    self.subplot_3d_wires = self.subplot.scatter(x_blue, y_blue, z_blue, s = 150, c = BLUE,  depthshade = False, lw = 0, alpha = 1)

    [...]

    return [self.subplot_3d_wires]

我想用一个滑动条something along this question逐渐替换动画,所以首先我只想在我的动画旁边添加一个滑块(from matplotlib.widgets import Slider),而不是以任何方式连接到动画。但是只要在图上声明silder,动画就会被破坏-我看到我的图一个一个叠加在另一个上面,看这个图。在

我试着用

 axcolor = 'lightgoldenrodyellow'
 axtime = plt.axes([0.25, 0.1, 0.65, 0.03])
 self.stime = Slider(axtime, 'Time', 0.0, 100.0, valinit = 50.0)

无论是在类MyAnim__init__中,还是当我为动画启动init方法时,它们都会产生相同的结果。在

我做错什么了?如有任何帮助,我们将不胜感激!在

Before the slider is added animation goes smoothly

with the slider the frames overlay one on top of the other


Tags: 方法posselfalphainitdefstep动画
1条回答
网友
1楼 · 发布于 2024-05-14 06:43:45

问题在于plt.cla()。 此命令将清除它在绘图上找到的最后一个活动的axes。添加滑块后,滑块的轴将是要清除的轴,绘图轴保持不变。在

因此,解决方案不是让pyplot决定清除哪个轴,而是明确地声明

self.subplot.cla()   

相关问题 更多 >