Matplotlib动画的奇怪行为

时间:2018-02-25 21:25:07

标签: python matplotlib jupyter

我正在制作一个涉及两个阶段的动画,一个"旋转"阶段和"淡出"相。初始图形如下所示: enter image description here

想要的首先旋转图形,使黑线在水平方向上。一旦完成,我想淡出红线和蓝点,所以只有红点和黑线可见。我尝试此操作的代码如下(这是在一个jupyter单元格中)。

data = m


def init():
    fig, ax = plt.subplots(1, 1, figsize=(8, 8))
    ax.set(xlim=(-1.2, 1.2), ylim=(-1.2, 1.2))
    ax.axis('off')

    # Calculate Projections
    best_u = get_best_u(m)
    projected_points = line_projection(best_u, m)

    projection_main_line, = ax.plot(projected_points[0], projected_points[1], c='black')
    projection_points, = ax.plot(projected_points[0], projected_points[1], 'or')


    projection_lines = []
    for i in range(projected_points.shape[1]):
        temp_line = ax.plot([m[0, i], projected_points[0, i]], [m[1, i], projected_points[1, i]], '-r')
        projection_lines.append(temp_line)

    data_line, = ax.plot(m[0], m[1], linestyle='', marker='o')
    proj_lines = update_helper(projection_lines, 0)
    return [data_line, projection_main_line, projection_points, *proj_lines]

def update_helper(projection_lines, i):
    return_list = []
    if i < len(projection_lines):
        line, = projection_lines[0]
        return [line]
    else:
        line, = projection_lines[i]
        return_list.append(line)
        next_list = update_helper(projection_lines, i+1)
        return return_list + next_list

def rotate_stage(deg, data):
    data = rotate_matrix(data, -deg).T
    best_u = get_best_u(data)
    projected_points = line_projection(best_u, data)
    projection_main_line.set_data(projected_points[0], projected_points[1])
    projection_points.set_data(projected_points[0], projected_points[1])
    for i in range(len(projection_lines)):
        line, = projection_lines[i]
        line.set_data(
            [data[0, i], projected_points[0, i]],[data[1, i], projected_points[1, i]]
        )


    data_line.set_data(data[0], data[1])

    proj_lines = update_helper(projection_lines, 0)
    return [data_line, projection_main_line, projection_points, *proj_lines]

def fade_stage(i):
    for i in range(len(projection_lines)):
        line, = projection_lines[i]
        line.set_alpha(max(1 - i*0.05, 0))

    data_line.set_alpha(max(1 - i*0.05, 0))

    proj_lines = update_helper(projection_lines, 0)
    return [data_line, *proj_lines]

def update(i, data):
    if i < 45:
        return rotate_stage(i, data)
    else:
        return fade_stage(i - 44)


anim = FuncAnimation(fig, update, interval=1, init_func=init, fargs=[data],frames=64, blit=True)
HTML(anim.to_html5_video())
anim.save('test.mp4', fps=20, dpi=80)

结果输出如下所示: Output

我不太明白为什么会发生这种情况 - 我认为它会首先循环旋转然后循环淡出,但显然不是发生了什么。任何见解都将不胜感激。

0 个答案:

没有答案