如何在交互式绘图(Python Matplotlib)中用鼠标指向(x,y)位置?

要在交互式绘图中获取鼠标指向的 (x, y) 位置,我们可以采取以下步骤

脚步

  • 设置图形大小并调整子图之间和周围的填充。

  • 创建新地物或激活现有地物。

  • 将函数*mouse_event*绑定到事件*button_press_event*

  • 使用 numpy创建xy数据点。

  • 使用方法绘制xy数据点plot()

  • 要显示图形,请使用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