matplotlib 点击鼠标显示标签坐标
时间: 2023-08-21 11:07:36 浏览: 102
显示鼠标坐标
要实现点击鼠标后显示标签坐标的功能,可以使用 Matplotlib 中的 `FigureCanvas` 和 `FigureCanvas.mpl_connect()` 方法来实现。具体步骤如下:
1. 导入必要的库:
```python
import matplotlib.pyplot as plt
import numpy as np
```
2. 创建一个绘图窗口和子图对象:
```python
fig, ax = plt.subplots()
```
3. 在子图中绘制数据:
```python
x = np.linspace(0, 10, 100)
y = np.sin(x)
ax.plot(x, y)
```
4. 定义一个回调函数,用于处理鼠标点击事件并显示标签坐标:
```python
def on_click(event):
if event.button == 1: # 左键点击
x, y = event.xdata, event.ydata
ax.text(x, y, f'({x:.2f}, {y:.2f})', ha='center', va='bottom')
fig.canvas.draw_idle()
```
5. 注册回调函数,监听鼠标点击事件:
```python
cid = fig.canvas.mpl_connect('button_press_event', on_click)
```
6. 显示绘图窗口:
```python
plt.show()
```
完整代码示例:
```python
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x = np.linspace(0, 10, 100)
y = np.sin(x)
ax.plot(x, y)
def on_click(event):
if event.button == 1: # 左键点击
x, y = event.xdata, event.ydata
ax.text(x, y, f'({x:.2f}, {y:.2f})', ha='center', va='bottom')
fig.canvas.draw_idle()
cid = fig.canvas.mpl_connect('button_press_event', on_click)
plt.show()
```
阅读全文