Python+matplotlib数据可视化鼠标悬停自动标注功能实现
时间: 2023-08-01 10:07:51 浏览: 226
基于PyQt5实现可视化自动标注工具可选择YOLOv5、YOLOv8或者自定义模型完整源码+数据.zip
5星 · 资源好评率100%
要实现Python+matplotlib数据可视化鼠标悬停自动标注功能,可以使用matplotlib中的annotate()函数,该函数可以在图形中添加注释文本。
具体实现步骤如下:
1. 导入必要的库:
```python
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
```
2. 创建图形并绘制数据:
```python
fig, ax = plt.subplots()
ax.plot(x_data, y_data)
```
3. 定义鼠标悬停事件的回调函数,该函数将在鼠标悬停时被调用,根据鼠标所在的数据点位置添加注释文本:
```python
def on_hover(event):
for i in range(len(x_data)):
if event.xdata is not None and event.ydata is not None:
if x_data[i] - 0.5 <= event.xdata <= x_data[i] + 0.5 and \
y_data[i] - 0.5 <= event.ydata <= y_data[i] + 0.5:
img = plt.imread(image_files[i])
imagebox = OffsetImage(img, zoom=0.2)
ab = AnnotationBbox(imagebox, (x_data[i], y_data[i]))
ax.add_artist(ab)
fig.canvas.draw_idle()
```
4. 将回调函数绑定到图形的鼠标悬停事件上:
```python
fig.canvas.mpl_connect('motion_notify_event', on_hover)
```
完整代码:
```python
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
x_data = [1, 2, 3, 4, 5]
y_data = [2, 4, 1, 5, 3]
image_files = ['image1.png', 'image2.png', 'image3.png', 'image4.png', 'image5.png']
fig, ax = plt.subplots()
ax.plot(x_data, y_data)
def on_hover(event):
for i in range(len(x_data)):
if event.xdata is not None and event.ydata is not None:
if x_data[i] - 0.5 <= event.xdata <= x_data[i] + 0.5 and \
y_data[i] - 0.5 <= event.ydata <= y_data[i] + 0.5:
img = plt.imread(image_files[i])
imagebox = OffsetImage(img, zoom=0.2)
ab = AnnotationBbox(imagebox, (x_data[i], y_data[i]))
ax.add_artist(ab)
fig.canvas.draw_idle()
fig.canvas.mpl_connect('motion_notify_event', on_hover)
plt.show()
```
执行该代码后,将会在图形中添加自动标注功能。当鼠标悬停在数据点附近时,会自动在该点添加注释文本,并显示与该数据点相关的图片。
阅读全文