为什么从FuncAnimation中保存的视频会是情节的叠加? [英] Why is the saved video from FuncAnimation a superpositions of plots?

查看:59
本文介绍了为什么从FuncAnimation中保存的视频会是情节的叠加?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我想问一下 Python 的 FuncAnimation.

Regards, I would like to ask about Python's FuncAnimation.

在完整代码中,我试图为条形图制作动画(用于整体说明).

In the full code, I was trying to animate bar plots (for integral illustration). The animated output from

ani = FuncAnimation(fig, update, frames=Iter, init_func = init, blit=True);
plt.show(ani);

看起来不错.

但是来自

ani.save("example_new.mp4", fps = 5)

给出了一个与 Python 中显示的动画略有不同的版本.与动画相比,输出给出了"叠加版本"的视频.与动画不同的是:在视频中,在每一帧中,之前的情节一直与当前的情节一起显示.

gives a slightly different version from the animation showed in Python. The output gives a video of 'superposition version' compared to the animation. Unlike the animation : in the video, at each frame, the previous plots kept showing together with the current one.

完整代码如下:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation


fig, ax = plt.subplots()
Num = 20
p = plt.bar([0], [0], 1, color = 'b')
Iter = tuple(range(2, Num+1))
xx = list(np.linspace(0, 2, 200)); yy = list(map(lambda x : x**2,xx));

def init(): 
    ax.set_xlim(0, 2)
    ax.set_ylim(0, 4)
    return (p)

def update(frame):
    w = 2/frame;
    X = list(np.linspace(0, 2-w, frame+1));
    Y = list(map(lambda x: x**2, X));
    X = list(map(lambda x: x + w/2,X));
    C = (0, 0, frame/Num); 
    L = plt.plot(xx , yy, 'y', animated=True)[0]
    p = plt.bar(X, Y, w, color = C, animated=True)
    P = list(p[:]); P.append(L)   
    return P

ani = FuncAnimation(fig, update, frames=Iter, init_func = init, interval = 0.25, blit=True)
ani.save("examplenew.mp4", fps = 5)
plt.show(ani)

对此的任何建设性意见将不胜感激.谢谢.问候,Arief.

Any constructive inputs on this would be appreciated. Thanks. Regards, Arief.

推荐答案

保存动画时,不使用提示音.您可以关闭 blitting,即 blit=False 并以与保存时相同的方式查看动画.

When saving the animation, no blitting is used. You can turn off blitting, i.e. blit=False and see the animation the same way as it is saved.

正在发生的事情是,在每次迭代中都会添加一个新图,而不会删除最后一个图.您基本上有两个选择:

What is happening is that in each iteration a new plot is added without the last one being removed. You basically have two options:

  1. 清除中间的轴,ax.clear()(然后记得再次设置轴限制)
  2. 更新条形图和绘图的数据.为此的示例:
  1. Clear the axes in between, ax.clear() (then remember to set the axes limits again)
  2. update the data for the bars and the plot. Examples to do this:
    • For plot: Matplotlib Live Update Graph
    • For bar: Dynamically updating a bar plot in matplotlib

这篇关于为什么从FuncAnimation中保存的视频会是情节的叠加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆