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
:它们是可以绘制在画布上的简单图形元素,例如Line2D
、Rectangle
、Text
、Image
等。 - 容器
Artist
:它们可以包含许多Artist
对象,使得它们可以组织在一起。例如Figure
、Axes
和Axis
。
在上面的动画例子中,ln
是一个Line2D
对象,它是一个基本的Artist
对象,代表了一个线条。在init
和update
函数中,我们需要返回一个Artist
对象或Artist
对象的可迭代序列,这样Matplotlib才能知道哪些部分需要被重绘。在这里,我们返回了一个包含ln
的元组,因此只有这个线条会被重绘。
在上面的代码中,init
和update
函数的返回值将被用于blitting。blitting用于提高动画的性能,它只重新绘制图形中发生变化的部分。为了实现这个功能,init
和update
函数需要返回一个包含所有需要被重绘的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,用来设置刷新频率