matplotlib 曲线上点击鼠标显示标签
时间: 2023-08-21 15:07:36 浏览: 62
可以使用 matplotlib 中的 `Annotation` 来实现在曲线上点击鼠标显示标签的功能。具体步骤如下:
1. 导入 matplotlib 和 numpy:
``` python
import matplotlib.pyplot as plt
import numpy as np
```
2. 创建一个简单的曲线图:
``` python
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
plt.plot(x, y)
```
3. 定义一个点击事件函数,用于在曲线上点击鼠标时显示标签:
``` python
def onclick(event):
x, y = event.xdata, event.ydata
annot.xy = (x, y)
text = f'({x:.2f}, {y:.2f})'
annot.set_text(text)
plt.draw()
```
4. 将点击事件函数绑定到图形上,并创建一个 `Annotation` 对象:
``` python
fig = plt.gcf()
ax = plt.gca()
annot = ax.annotate("", xy=(0,0), xytext=(-20,20), textcoords="offset points",
bbox=dict(boxstyle="round", fc="w"),
arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)
cid = fig.canvas.mpl_connect('button_press_event', onclick)
```
5. 显示图形:
``` python
plt.show()
```
完整代码如下:
``` python
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
plt.plot(x, y)
def onclick(event):
x, y = event.xdata, event.ydata
annot.xy = (x, y)
text = f'({x:.2f}, {y:.2f})'
annot.set_text(text)
plt.draw()
fig = plt.gcf()
ax = plt.gca()
annot = ax.annotate("", xy=(0,0), xytext=(-20,20), textcoords="offset points",
bbox=dict(boxstyle="round", fc="w"),
arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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_column_c1.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)