微信扫一扫打赏支持

matplotlib库疑难问题---4、画动态图

matplotlib库疑难问题---4、画动态图

一、总结

一句话总结:

主要是弄懂animation模块FuncAnimation函数,弄懂函数对应那些参数的意思就很简单了:animation.FuncAnimation(fig=fig,func=animate,frames=100,init_func=init,interval=20,blit=True)
"""
fig:figure对象
animate:动画函数,不断更新图像的函数,生成新的xdata和ydata
frames:动画的帧数
init_func=init:动画初始化函数为init,自定义开始帧。
interval=20:动画每一帧时间间隔为20ms,interval的单位以ms计算。
blit=True:选择更新所有点,还是仅更新产生变化的点。应选择True,但mac用户请选择False,否则无法显示。
"""

 

 

 

 

二、画动态图

博客对应课程的视频位置:4、画动态图-范仁义-读书编程笔记
https://www.fanrenyi.com/video/43/374

 

1、matplotlib动画样例

In [1]:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
# 激活matplotlib后端的渲染引擎qt5
%matplotlib qt5

x=np.arange(0,2*np.pi,0.01)
y=np.sin(x)
fig=plt.figure()
line,=plt.plot(x,y)

# 动画函数
def animate(i):
    line.set_ydata(np.sin(x+i/100))
    return line,

# 动画初始函数
def init():
    line.set_ydata(np.sin(x))
    return line,


"""
fig:figure对象
animate:动画函数,不断更新图像的函数,生成新的xdata和ydata
frames:动画的帧数
init_func=init:动画初始化函数为init,自定义开始帧。
interval=20:动画每一帧时间间隔为20ms,interval的单位以ms计算。
blit=True:选择更新所有点,还是仅更新产生变化的点。应选择True,但mac用户请选择False,否则无法显示。
"""
# 现在frames=100,interval=20,动画有100帧,每帧20ms,所以动画总共持续2s
ani=animation.FuncAnimation(fig=fig,func=animate,frames=100,init_func=init,interval=20,blit=True)
plt.show()

2、动手写一个动画

In [1]:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
#%matplotlib qt5
%pylab

x=np.arange(0,2*np.pi,0.01)
y=np.sin(x)
fig=plt.figure()
line,=plt.plot(x,y)

# 动画函数
def animate(i):
    line.set_ydata(np.sin(x+i/10))
    return line,

# 动画初始化函数
def init():
    line.set_ydata(np.sin(x))
    return line,

animation.FuncAnimation(fig=fig,func=animate,frames=100,init_func=init,interval=20,blit=True)

plt.show()
Using matplotlib backend: Qt5Agg
Populating the interactive namespace from numpy and matplotlib
In [3]:
help(animation.FuncAnimation)
Help on class FuncAnimation in module matplotlib.animation:

class FuncAnimation(TimedAnimation)
 |  FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True, **kwargs)
 |  
 |  Makes an animation by repeatedly calling a function *func*.
 |  
 |  Parameters
 |  ----------
 |  fig : `~matplotlib.figure.Figure`
 |     The figure object that is used to get draw, resize, and any
 |     other needed events.
 |  
 |  func : callable
 |     The function to call at each frame.  The first argument will
 |     be the next value in *frames*.   Any additional positional
 |     arguments can be supplied via the *fargs* parameter.
 |  
 |     The required signature is::
 |  
 |        def func(frame, *fargs) -> iterable_of_artists
 |  
 |     If ``blit == True``, *func* must return an iterable of all artists
 |     that were modified or created. This information is used by the blitting
 |     algorithm to determine which parts of the figure have to be updated.
 |     The return value is unused if ``blit == False`` and may be omitted in
 |     that case.
 |  
 |  frames : iterable, int, generator function, or None, optional
 |      Source of data to pass *func* and each frame of the animation
 |  
 |      - If an iterable, then simply use the values provided.  If the
 |        iterable has a length, it will override the *save_count* kwarg.
 |  
 |      - If an integer, then equivalent to passing ``range(frames)``
 |  
 |      - If a generator function, then must have the signature::
 |  
 |           def gen_function() -> obj
 |  
 |      - If *None*, then equivalent to passing ``itertools.count``.
 |  
 |      In all of these cases, the values in *frames* is simply passed through
 |      to the user-supplied *func* and thus can be of any type.
 |  
 |  init_func : callable, optional
 |     A function used to draw a clear frame. If not given, the
 |     results of drawing from the first item in the frames sequence
 |     will be used. This function will be called once before the
 |     first frame.
 |  
 |     The required signature is::
 |  
 |        def init_func() -> iterable_of_artists
 |  
 |     If ``blit == True``, *init_func* must return an iterable of artists
 |     to be re-drawn. This information is used by the blitting
 |     algorithm to determine which parts of the figure have to be updated.
 |     The return value is unused if ``blit == False`` and may be omitted in
 |     that case.
 |  
 |  fargs : tuple or None, optional
 |     Additional arguments to pass to each call to *func*.
 |  
 |  save_count : int, optional
 |     The number of values from *frames* to cache.
 |  
 |  interval : number, optional
 |     Delay between frames in milliseconds.  Defaults to 200.
 |  
 |  repeat_delay : number, optional
 |     If the animation in repeated, adds a delay in milliseconds
 |     before repeating the animation.  Defaults to *None*.
 |  
 |  repeat : bool, optional
 |     Controls whether the animation should repeat when the sequence
 |     of frames is completed.  Defaults to *True*.
 |  
 |  blit : bool, optional
 |     Controls whether blitting is used to optimize drawing. Note: when using
 |     blitting any animated artists will be drawn according to their zorder.
 |     However, they will be drawn on top of any previous artists, regardless
 |     of their zorder.  Defaults to *False*.
 |  
 |  cache_frame_data : bool, optional
 |     Controls whether frame data is cached. Defaults to *True*.
 |     Disabling cache might be helpful when frames contain large objects.
 |  
 |  Method resolution order:
 |      FuncAnimation
 |      TimedAnimation
 |      Animation
 |      builtins.object
 |  
 |  Methods defined here:
 |  
 |  __init__(self, fig, func, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  new_frame_seq(self)
 |      Return a new sequence of frame information.
 |  
 |  new_saved_frame_seq(self)
 |      Return a new sequence of saved/cached frame information.
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from Animation:
 |  
 |  save(self, filename, writer=None, fps=None, dpi=None, codec=None, bitrate=None, extra_args=None, metadata=None, extra_anim=None, savefig_kwargs=None, *, progress_callback=None)
 |      Save the animation as a movie file by drawing every frame.
 |      
 |      Parameters
 |      ----------
 |      
 |      filename : str
 |          The output filename, e.g., :file:`mymovie.mp4`.
 |      
 |      writer : :class:`MovieWriter` or str, optional
 |          A `MovieWriter` instance to use or a key that identifies a
 |          class to use, such as 'ffmpeg'. If ``None``, defaults to
 |          :rc:`animation.writer` = 'ffmpeg'.
 |      
 |      fps : number, optional
 |         Frames per second in the movie. Defaults to ``None``, which will use
 |         the animation's specified interval to set the frames per second.
 |      
 |      dpi : number, optional
 |         Controls the dots per inch for the movie frames.  This combined with
 |         the figure's size in inches controls the size of the movie.  If
 |         ``None``, defaults to :rc:`savefig.dpi`.
 |      
 |      codec : str, optional
 |         The video codec to be used. Not all codecs are supported
 |         by a given :class:`MovieWriter`. If ``None``, default to
 |         :rc:`animation.codec` = 'h264'.
 |      
 |      bitrate : number, optional
 |         Specifies the number of bits used per second in the compressed
 |         movie, in kilobits per second. A higher number means a higher
 |         quality movie, but at the cost of increased file size. If ``None``,
 |         defaults to :rc:`animation.bitrate` = -1.
 |      
 |      extra_args : list, optional
 |         List of extra string arguments to be passed to the underlying movie
 |         utility. If ``None``, defaults to :rc:`animation.extra_args`.
 |      
 |      metadata : Dict[str, str], optional
 |         Dictionary of keys and values for metadata to include in
 |         the output file. Some keys that may be of use include:
 |         title, artist, genre, subject, copyright, srcform, comment.
 |      
 |      extra_anim : list, optional
 |         Additional `Animation` objects that should be included
 |         in the saved movie file. These need to be from the same
 |         `matplotlib.figure.Figure` instance. Also, animation frames will
 |         just be simply combined, so there should be a 1:1 correspondence
 |         between the frames from the different animations.
 |      
 |      savefig_kwargs : dict, optional
 |         Is a dictionary containing keyword arguments to be passed
 |         on to the `savefig` command which is called repeatedly to
 |         save the individual frames.
 |      
 |      progress_callback : function, optional
 |          A callback function that will be called for every frame to notify
 |          the saving progress. It must have the signature ::
 |      
 |              def func(current_frame: int, total_frames: int) -> Any
 |      
 |          where *current_frame* is the current frame number and
 |          *total_frames* is the total number of frames to be saved.
 |          *total_frames* is set to None, if the total number of frames can
 |          not be determined. Return values may exist but are ignored.
 |      
 |          Example code to write the progress to stdout::
 |      
 |              progress_callback =                    lambda i, n: print(f'Saving frame {i} of {n}')
 |      
 |      Notes
 |      -----
 |      *fps*, *codec*, *bitrate*, *extra_args* and *metadata* are used to
 |      construct a `.MovieWriter` instance and can only be passed if
 |      *writer* is a string.  If they are passed as non-*None* and *writer*
 |      is a `.MovieWriter`, a `RuntimeError` will be raised.
 |  
 |  to_html5_video(self, embed_limit=None)
 |      Convert the animation to an HTML5 ``<video>`` tag.
 |      
 |      This saves the animation as an h264 video, encoded in base64
 |      directly into the HTML5 video tag. This respects the rc parameters
 |      for the writer as well as the bitrate. This also makes use of the
 |      ``interval`` to control the speed, and uses the ``repeat``
 |      parameter to decide whether to loop.
 |      
 |      Parameters
 |      ----------
 |      embed_limit : float, optional
 |          Limit, in MB, of the returned animation. No animation is created
 |          if the limit is exceeded.
 |          Defaults to :rc:`animation.embed_limit` = 20.0.
 |      
 |      Returns
 |      -------
 |      video_tag : str
 |          An HTML5 video tag with the animation embedded as base64 encoded
 |          h264 video.
 |          If the *embed_limit* is exceeded, this returns the string
 |          "Video too large to embed."
 |  
 |  to_jshtml(self, fps=None, embed_frames=True, default_mode=None)
 |      Generate HTML representation of the animation
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from Animation:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

In [ ]:
 
 

本系列博客对应课程位置:
1、解决中文乱码问题-范仁义-读书编程笔记
https://www.fanrenyi.com/video/43/371
2、将曲线平滑-范仁义-读书编程笔记
https://www.fanrenyi.com/video/43/372
3、matplotlib绘图核心原理-范仁义-读书编程笔记
https://www.fanrenyi.com/video/43/373
4、画动态图-范仁义-读书编程笔记
https://www.fanrenyi.com/video/43/374
5、保存动态图-范仁义-读书编程笔记
https://www.fanrenyi.com/video/43/375
6、显示图片-范仁义-读书编程笔记
https://www.fanrenyi.com/video/43/376

7、去掉刻度和边框-范仁义-读书编程笔记
https://www.fanrenyi.com/video/43/383

8、几个点画曲线-范仁义-读书编程笔记
https://www.fanrenyi.com/video/43/384

9、画箭头(综合实例)-1-范仁义-读书编程笔记
https://www.fanrenyi.com/video/43/391

9、画箭头(综合实例)-2-范仁义-读书编程笔记
https://www.fanrenyi.com/video/43/392

10、画直方图-范仁义-读书编程笔记
https://www.fanrenyi.com/video/43/393

11、画动态直方图-范仁义-读书编程笔记
https://www.fanrenyi.com/video/43/394

posted @ 2020-10-23 21:18  范仁义  阅读(254)  评论(0编辑  收藏  举报