matplotlib 鼠标悬停显示标签
时间: 2023-07-22 20:04:43 浏览: 229
在 `matplotlib` 中,可以通过 `annotate` 和 `text` 方法来添加标签,然后使用 `mpldatacursor` 或 `mplcursors` 库来实现鼠标悬停显示标签的效果。
以下是使用 `mplcursors` 库的示例代码:
```python
import matplotlib.pyplot as plt
import mplcursors
fig, ax = plt.subplots()
lines = ax.plot([0, 1, 2], [0, 1, 2])
mplcursors.cursor(lines)
plt.show()
```
运行上述代码后,当鼠标悬停在图形上时,会显示每个点的坐标。
如果要自定义标签内容,可以在 `cursor` 方法中传入一个回调函数,例如:
```python
import matplotlib.pyplot as plt
import mplcursors
fig, ax = plt.subplots()
lines = ax.plot([0, 1, 2], [0, 1, 2])
def on_hover(sel):
x, y, _ = sel.target
sel.annotation.set_text(f"({x:.2f}, {y:.2f})")
cursor = mplcursors.cursor(lines).connect("add", on_hover)
plt.show()
```
这样鼠标悬停在图形上时,会显示每个点的坐标,格式为 `(x, y)`。
阅读全文
相关推荐


















