使用 Matplotlib 存储鼠标点击事件坐标
要将鼠标事件坐标存储到 Matplotlib 中,我们可以使用 "button_press_event" 事件。−
步骤
- 设置图形尺寸,并调整子图之间的内边距和四周内边距。
- 创建一个图形和一组子图。
- 在 10 的范围内绘制一条线
- 将函数 *onclick* 绑定到事件 *button_press_event*。
- 打印事件的 x 和 y 数据。
- 要显示图形,请使用 show() 方法。
示例
from matplotlib import pyplot as plt
plt.rcParams['backend'] = 'TkAgg'
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Function to print mouse click event coordinates
def onclick(event):
print([event.xdata, event.ydata])
# Create a figure and a set of subplots
fig, ax = plt.subplots()
# Plot a line in the range of 10
ax.plot(range(10))
# Bind the button_press_event with the onclick() method
fig.canvas.mpl_connect('button_press_event', onclick)
# Display the plot
plt.show()输出
执行后,它将产生以下输出

现在,点击图中的任意位置,它将显示控制台中该点的坐标
[6.277811659536052 6.218189947945731] [4.9416949672083685 3.7079096112932475] [8.221254287227506 3.4145010811941963]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP