如何在互動式繪圖中獲取滑鼠指向的 (x,y) 位置(Python Matplotlib)?


要獲取互動繪圖裡滑鼠指向的 (x, y) 位值,我們可以執行以下步驟

步驟

  • 設定圖片尺寸並調整子圖之間的內邊距。

  • 建立一個新圖片或啟用一個現有圖片。

  • 將函式 *mouse_event* 繫結到事件 *button_press_event*

  • 使用 numpy 建立 xy 資料點。

  • 使用 plot() 方法繪製 xy 資料點。

  • 要顯示圖片,使用 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()

輸出

它將產生以下輸出 −

現在,單擊繪圖上的任意位置,它將在控制檯上顯示點的座標 −

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

更新於: 2021 年 10 月 19 日

4K+ 閱讀

開啟你的職業生涯

完成課程獲取認證

開始
廣告