Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Định nghĩa nhiều plot để animate với vòng lặp for trong Matplotlib

Để định nghĩa nhiều plot để animate với vòng lặp for trong matplotlib:

  • Thiết lập kích thước hình và điều chỉnh khoảng đệm subplot.
  • Tạo figure mới hoặc kích hoạt figure hiện có.
  • Thêm axes vào figure hiện tại.
  • Khởi tạo biến N và x bằng numpy.
  • Lấy danh sách lines và bar patches.
  • Animate lines và rectangles (bar patches) trong vòng lặp for.
  • Tạo animation bằng FuncAnimation gọi lại hàm.
  • Hiển thị hình bằng show().

Ví dụ

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()

Kết quả

Định nghĩa nhiều plot để animate với vòng lặp for trong Matplotlib