文章目录
1、matplotlib.animation
1.1、FuncAnimation
matplotlib.animation.FuncAnimation
是 Matplotlib 库中用于创建动画的一个类。它允许你通过循环调用一个函数来更新图表,从而生成动画效果。这个函数通常被称为“更新函数”,它决定了每一帧图表的样子。FuncAnimation 类提供了一种灵活而强大的方式来创建和展示动画,使得数据可视化更加生动和直观。
(1)基本用法
使用 FuncAnimation 创建动画的基本步骤如下:
- 准备数据:首先,你需要准备好用于动画的数据。这可能包括一系列的X和Y坐标点、颜色、大小等,具体取决于你要制作的动画类型。
- 创建图形和轴:使用 Matplotlib 创建图形(Figure)和轴(Axes)对象,这些对象将作为动画的画布。
- 定义更新函数:编写一个函数,这个函数接受当前的帧号(或其他参数)作为输入,并返回一个更新后的图形元素状态。例如,如果你正在制作一个点的移动动画,这个函数可能会更新点的位置。
- 创建 FuncAnimation 对象:使用 FuncAnimation 类创建一个动画对象。你需要指定图形对象、轴对象、更新函数、帧数(或时间间隔)、以及其他可选参数(如重复次数、初始延迟等)。
- 显示或保存动画:最后,你可以使用 Matplotlib 的显示功能(如 plt.show())来查看动画,或者将其保存为文件(如GIF、MP4等)。
(2)示例代码
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# 准备数据
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
# 创建图形和轴
fig, ax = plt.subplots()
line, = ax.plot([], [], 'r-') # 初始化一个空线条对象
ax.set_xlim(0, 2 * np.pi) # 设置X轴范围
ax.set_ylim(-1.5, 1.5) # 设置Y轴范围
# 定义更新函数
def update(frame):
line.set_data(x[:frame], y[:frame]) # 更新线条数据
return line,
# 创建 FuncAnimation 对象
ani = FuncAnimation(fig, update, frames=len(x), interval=50, blit=True)
# 显示动画
plt.show()
在这个例子中,update 函数根据当前的帧号(frame)更新线条的数据,使得线条逐渐变长,模拟了一个点沿正弦曲线移动的动画效果。
再看一个例子
#coding=utf-8
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))
def animate(i):
line.set_ydata(np.sin(x + i/10.0))
return line,
def init():
line.set_ydata(np.ma.array(x, mask=True))
return line,
ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init,
interval=25, blit=True)
ani.save("animation.gif", writer="imagemagick", fps=30)
plt.show()
(3)matplotlib.animation.FuncAnimation
class matplotlib.animation.FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True, **kwargs)
def __init__(self,
fig: Figure,
func: (...) -> Iterable[Artist],
frames: Iterable | int | () -> Generator | None = ...,
init_func: () -> Iterable[Artist] | None = ...,
fargs: tuple[Any, ...] | None = ...,
save_count: int | None = ...,
*,
cache_frame_data: bool = ...,
**kwargs: Any) -> None
`TimedAnimation` subclass that makes an animation by repeatedly calling a function *func*. .. note:: You must store the created Animation in a variable that lives as long as the animation should run. Otherwise, the Animation object will be garbage-collected and the animation stops. Parameters ---------- fig : `~matplotlib.figure.Figure` The figure object used to get needed events, such as draw or resize. 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 using `functools.partial` or via the *fargs* parameter. The required signature is:: def func(frame, *fargs) -> iterable_of_artists It is often more convenient to provide the arguments using `functools.partial`. In this way it is also possible to pass keyword arguments. To pass a function with both positional and keyword arguments, set all arguments as keyword arguments, just leaving the *frame* argument unset:: def func(frame, art, *, y=None): ... ani = FuncAnimation(fig, partial(func, art=ln, y='foo')) 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