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

Di chuyển trục X trong Matplotlib khi vẽ real-time


Để di chuyển trục X trong Matplotlib khi vẽ real-time, chúng ta có thể thực hiện các bước sau:

  • Thiết lập kích thước figure và điều chỉnh padding giữa và xung quanh subplots.
  • Tạo figure và tập subplots.
  • Tạo điểm dữ liệu x và y bằng numpy.
  • Vẽ x và y bằng phương thức plot().
  • Tạo animation bằng cách gọi liên tục hàm animate di chuyển trục X khi vẽ real-time.
  • Để hiển thị figure, dùng phương thức show().

Ví dụ

import matplotlib.pylab as plt
import matplotlib.animation as animation
import numpy as np

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

fig, ax = plt.subplots()
x = np.linspace(0, 15, 100)
y = np.cos(x)
ax.plot(x, y, lw=2, color='red')

def animate(frame):
    ax.set_xlim(left=0, right=frame)

ani = animation.FuncAnimation(fig, animate, frames=10)
plt.show()

Kết quả

Di chuyển trục X trong Matplotlib khi vẽ real-time