如何使用Matplotlib动画更新绘图标题?
要使用Matplotlib动画更新绘图标题,我们可以采取以下步骤−
- 设置图形大小并调整子图之间和周围的填充。
- 使用 figure() 方法创建新图或激活现有图。
- 使用numpy创建 x 和 y 数据点。
- 获取当前轴。
- 使用 text() 方法向轴添加文本。
- 添加一个可以通过重复调用函数来制作动画的动画方法。
- 使用 show() 方法显示图形。
示例
import numpy as np
from matplotlib import pyplot as plt, animation
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
x = np.linspace(-10, 10, 1000)
y = np.sin(x)
plt.plot(x, y)
ax = plt.gca()
ax.text(0.5, 1.100, "y=sin(x)", bbox={'facecolor': 'red',
'alpha': 0.5, 'pad': 5},
transform=ax.transAxes, ha="center")
def animate(frame):
ax.text(0.5, 1.100, "y=sin(x), frame: %d" % frame,
bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 5},
transform=ax.transAxes, ha="center")
ani = animation.FuncAnimation(fig, animate, interval=100,
frames=10, repeat=True)
plt.show()