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

Cuộn lùi/to tiến giữa các biểu đồ Matplotlib

Để cuộn lùi/to tiến (phím mũi tên trái/phải) qua các biểu đồ Matplotlib:

  • Thiết lập kích thước hình và điều chỉnh khoảng đệm subplot.
  • Tạo curr_pos và y bằng numpy.
  • Tạo figure mới hoặc kích hoạt figure hiện có bằng figure().
  • Gắn hàm xử lý sự kiện key_press_event.
  • Thêm axes vào figure như một subplot.
  • Vẽ dữ liệu curr_pos và y bằng plot().
  • Nếu nhấn mũi tên trái/phải, đường cong sẽ dịch chuyển tương ứng.
  • Hiển thị hình bằng show().

Ví dụ

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
curr_pos = np.linspace(-10, 10, 100)
y = np.sin(curr_pos)
def key_event(e):
    global curr_pos
    if e.key == "right":
        curr_pos = curr_pos + 1
    else:
        curr_pos = curr_pos - 1
    ax.cla()
    ax.plot(curr_pos, np.sin(curr_pos))
    fig.canvas.draw()
fig = plt.figure()
fig.canvas.mpl_connect('key_press_event', key_event)
ax = fig.add_subplot(111)
ax.plot(curr_pos, y)
plt.show()

Kết quả

Cuộn lùi/to tiến giữa các biểu đồ Matplotlib

Bây giờ, nhấn phím mũi tên trái hoặc phải để cuộn lùi/to tiến qua biểu đồ.