matplotlib 曲线上点击鼠标显示自定义标注
时间: 2023-10-02 08:04:20 浏览: 53
要在 matplotlib 曲线上添加自定义标注,可以使用 matplotlib 的事件处理机制来捕捉鼠标点击事件。具体的步骤如下:
1. 导入 matplotlib 和 numpy 库。
```python
import matplotlib.pyplot as plt
import numpy as np
```
2. 创建一个 matplotlib 的 figure 和 axes 对象,并绘制曲线。
```python
fig, ax = plt.subplots()
x = np.linspace(0, 10, 1000)
y = np.sin(x)
ax.plot(x, y)
```
3. 定义一个函数 `onclick`,它将被调用当鼠标点击事件发生时。该函数需要获取鼠标点击的坐标,然后在这个坐标上添加一个自定义的标注。
```python
def onclick(event):
# 获取鼠标点击的坐标
x, y = event.xdata, event.ydata
# 添加自定义标注
ax.annotate('(%s, %s)' % (x, y),
xy=(x, y), xycoords='data',
xytext=(-50, 30), textcoords='offset points',
arrowprops=dict(arrowstyle="->"))
# 更新图形
fig.canvas.draw()
```
在这个函数中,我们使用 `ax.annotate` 方法来添加自定义标注。该方法的参数包括标注文本,标注位置,箭头属性等等。最后,我们需要调用 `fig.canvas.draw()` 来更新图形。
4. 注册事件处理函数。
```python
cid = fig.canvas.mpl_connect('button_press_event', onclick)
```
这一行代码将 `onclick` 函数注册为鼠标点击事件的处理函数。当用户在图形上点击鼠标时,`onclick` 函数将被调用。
5. 显示图形。
```python
plt.show()
```
完整的代码如下所示:
```python
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x = np.linspace(0, 10, 1000)
y = np.sin(x)
ax.plot(x, y)
def onclick(event):
x, y = event.xdata, event.ydata
ax.annotate('(%s, %s)' % (x, y),
xy=(x, y), xycoords='data',
xytext=(-50, 30), textcoords='offset points',
arrowprops=dict(arrowstyle="->"))
fig.canvas.draw()
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)