ใช้ Event Handling เพื่อจับตำแหน่งเมาส์เมื่อคลิกบนกราฟ
ขั้นตอน
- ตั้งค่าขนาด Figure
- สร้าง Figure
- ผูกฟังก์ชัน
mouse_eventกับ Event'button_press_event' - สร้างข้อมูล X, Y ด้วย NumPy
- วาดกราฟด้วย
plot() - แสดงผลด้วย
plt.show()
ตัวอย่างโค้ด
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()ผลลัพธ์
คลิกที่กราฟจะแสดงพิกัดใน 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
