matplotlib的动图介绍--animation

matplotlib的animation

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

fig, ax = plt.subplots()
xdata, ydata1, ydata2 = [], [], []
ln1, = plt.plot([], [], 'r-', label='sin')
ln2, = plt.plot([], [], 'b-', label='cos')

def init():
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)
    ax.legend()
    return ln1, ln2

def update(frame):
    xdata.append(frame)
    ydata1.append(np.sin(frame))
    ydata2.append(np.cos(frame))
    ln1.set_data(xdata, ydata1)
    ln2.set_data(xdata, ydata2)
    return ln1, ln2

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
                    init_func=init, blit=True)
plt.show()

在Matplotlib中,所有的图形和文本都是由Artist对象来表示和绘制的。Artist是一个非常重要的抽象概念,它代表了图形上的几乎所有元素。例如,图形(Figure)、子图(Axes)、线条(Line2D)、文字(Text)、图例(Legend)等等都是Artist对象。

Artist对象分为两种:基本Artist和容器Artist

  • 基本Artist:它们是可以绘制在画布上的简单图形元素,例如Line2DRectangleTextImage等。
  • 容器Artist:它们可以包含许多Artist对象,使得它们可以组织在一起。例如FigureAxesAxis

在上面的动画例子中,ln是一个Line2D对象,它是一个基本的Artist对象,代表了一个线条。在initupdate函数中,我们需要返回一个Artist对象或Artist对象的可迭代序列,这样Matplotlib才能知道哪些部分需要被重绘。在这里,我们返回了一个包含ln的元组,因此只有这个线条会被重绘。

在上面的代码中,initupdate函数的返回值将被用于blitting。blitting用于提高动画的性能,它只重新绘制图形中发生变化的部分。为了实现这个功能,initupdate函数需要返回一个包含所有需要被重绘的Artist对象的可迭代序列。

ln放在一个元组或列表中,然后返回这个元组或列表。例如,你可以返回(ln,)[ln]。这样,Matplotlib就能迭代这个返回值,并正确地找到所有需要被重绘的Artist对象。

例子2

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

fig, ax = plt.subplots()

# Create a circle and a text inside this circle
circle_radius = 0.5
circle = Circle((0.5, 0.5), circle_radius, fill=False)
text = ax.text(0.5, 0.5, "", ha='center', va='center', fontsize=12)
ax.add_patch(circle)

# Set limits and properties of the subplot
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_aspect('equal')
ax.axis('off')

def init():
    # This function is called at the beginning of the animation.
    # We use it to initialize the circle and the text.
    circle.center = (0.5, 0.5)
    text.set_text("")
    return circle, text

def update(frame):
    # This function is called for each frame of the animation.
    # We use it to update the position of the circle and the text.
    x = 0.5 + circle_radius * np.cos(frame)
    y = 0.5 + circle_radius * np.sin(frame)
    circle.center = (x, y)
    text.set_position((x, y))
    text.set_text(f"({x:.2f}, {y:.2f})")
    return circle, text

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 120),
                    init_func=init, blit=True,interval=50)
plt.show()

interval参数单位为ms,用来设置刷新频率

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值