在 Matplotlib 中用 for 循环定义要动画化的多个图

matplotlibpythondata visualization

要在 matplotlib 中用 for 循环定义要动画化的多个图,我们可以采取以下步骤 −

  • 设置图形大小并调整子图之间和周围的填充。
  • 使用 figure 方法创建新图形或激活现有图形。
  • 向当前图形添加轴并使其成为当前轴。
  • 使用 numpy 初始化两个变量 Nx
  • 获取线条和条形图块的列表。
  • for 循环中为线条和矩形(条形图块)制作动画。
  • 通过重复调用函数 *func* 制作动画。
  • 要显示图形,使用 show() 方法。

示例

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

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(0, 100))
N = 4
x = np.linspace(-5, 5, 100)
lines = [plt.plot(x, np.sin(x))[0] for _ in range(N)]
rectangles = plt.bar([0.5, 1, 1.5], [50, 40, 90], width=0.1)
patches = lines + list(rectangles)

def animate(i):
   for j, line in enumerate(lines):
      line.set_data([0, 2, i, j], [0, 3, 10 * j, i])
   for j, rectangle in enumerate(rectangles):
      rectangle.set_height(i / (j + 1))
return patches

anim = animation.FuncAnimation(fig, animate,
                                frames=100, interval=20, blit=True)

plt.show()

输出


相关文章