Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีดึงพิกัด (x,y) จากเมาส์ใน Interactive Plot (Python Matplotlib)

ใช้ Event Handling เพื่อจับตำแหน่งเมาส์เมื่อคลิกบนกราฟ

ขั้นตอน

  1. ตั้งค่าขนาด Figure
  2. สร้าง Figure
  3. ผูกฟังก์ชัน mouse_event กับ Event 'button_press_event'
  4. สร้างข้อมูล X, Y ด้วย NumPy
  5. วาดกราฟด้วย plot()
  6. แสดงผลด้วย 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

วิธีดึงพิกัด (x,y) จากเมาส์ใน Interactive Plot (Python Matplotlib)