Để lấy tọa độ (x, y) tại vị trí con trỏ chuột click trên biểu đồ tương tác, ta làm theo các bước:
Các bước thực hiện
- Thiết lập kích thước hình và padding
- Tạo hình mới hoặc kích hoạt hình hiện có
- Gán hàm mouse_event cho sự kiện button_press_event
- Tạo dữ liệu x và y bằng numpy
- Vẽ đồ thị bằng
plot() - Hiển thị bằng
show()
Ví dụ minh họa
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
def mouse_event(event):
print('x: {} and y: {}'.format(event.xdata, event.ydata))
fig = plt.figure()
cid = fig.canvas.mpl_connect('button_press_event', mouse_event)
x = np.linspace(-10, 10, 100)
y = np.exp(x)
plt.plot(x, y)
plt.show()
Đầu ra
Khi click vào đồ thị, tọa độ sẽ in ra console:
x: -3.633289020076159 and y: 7344.564590474489 x: 3.2193731551790172 and y: 3255.6463283494704 x: 8.680088326085489 and y: 802.2953710744596 x: 7.680741758860773 and y: 11269.926122114506 x: 0.6139338906288732 and y: 16503.741497634528
