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

Cách thêm con trỏ (cursor) cho đường cong trong Matplotlib?


Để thêm con trỏ cho đường cong trong Matplotlib, 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 điểm dữ liệu t và s bằng numpy.
  • Tạo một figure và một tập subplots.
  • Lấy instance của lớp Cursor, để cập nhật điểm con trỏ trên biểu đồ.
  • Trong mouse_event, lấy dữ liệu x và y của vị trí hiện tại của chuột.
    • Lấy chỉ số của điểm dữ liệu x và y.
    • Đặt vị trí x và y.
    • Đặt vị trí text và vẽ lại agg buffer và mouse event.
  • Vẽ t và s bằng phương thức plot().
  • Thiết lập một số thuộc tính trục.
  • Để hiển thị figure, dùng phương thức show().

Ví dụ

import matplotlib.pyplot as plt
import numpy as np

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

class CursorClass(object):
    def __init__(self, ax, x, y):
        self.ax = ax
        self.ly = ax.axvline(color='yellow', alpha=0.5)
        self.marker, = ax.plot([0], [0], marker="o", color="red", zorder=3)
        self.x = x
        self.y = y
        self.txt = ax.text(0.7, 0.9, '')

    def mouse_event(self, event):
        if event.inaxes:
            x, y = event.xdata, event.ydata
            indx = np.searchsorted(self.x, [x])[0]
            x = self.x[indx]
            y = self.y[indx]
            self.ly.set_xdata(x)
            self.marker.set_data([x], [y])
            self.txt.set_text('x=%1.2f, y=%1.2f' % (x, y))
            self.txt.set_position((x, y))
            self.ax.figure.canvas.draw_idle()
        else:
            return

t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2 * 2 * np.pi * t)

fig, ax = plt.subplots()
cursor = CursorClass(ax, t, s)
cid = plt.connect('motion_notify_event', cursor.mouse_event)
ax.plot(t, s, lw=2, color='green')
plt.axis([0, 1, -1, 1])
plt.show()

Kết quả

Cách thêm con trỏ (cursor) cho đường cong trong Matplotlib?Cách thêm con trỏ (cursor) cho đường cong trong Matplotlib?