python - Jupyter notebook 在(imshow)图上移动矩形
问题描述
我绘制一个 nd 数组,并在一个固定点显示一个矩形。但是我希望能够移动矩形(当我移动鼠标时),并显示一些东西(根据鼠标/矩形的坐标)。有没有办法在 Jupyter 笔记本中实现这样的事情?
解决方案
mplcursors可以显示交互式注释以及额外的元素。在下面的演示中,注释显示当前单元格的值以及周围单元格的平均值。矩形表示所选区域。
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import mplcursors
def show_rect(sel):
x, y = sel.target
i, j = sel.target.index
i0 = i if i == 0 else i - 1
i1 = i if i == M.shape[0] - 1 else i + 1
j0 = j if j == 0 else j - 1
j1 = j if j == M.shape[1] - 1 else j + 1
annotation_text = f'{i},{j}: {M[sel.target.index]}\nRegion mean: {M[i0:i1 + 1, j0:j1 + 1].mean():.2f}'
sel.annotation.set_text(annotation_text)
rect = Rectangle((j0 - 0.5, i0 - 0.5), j1 - j0 + 1, i1 - i0 + 1,
edgecolor='lime', linewidth=3, facecolor='none', clip_on=False)
ax.add_artist(rect)
sel.extras.append(rect)
fig, ax = plt.subplots(figsize=(9, 3))
M = np.random.randint(1, 101, size=(8, 12))
img = ax.imshow(M, cmap='coolwarm', vmin=0, vmax=100, aspect='auto')
plt.colorbar(img, ax=ax)
cursor = mplcursors.cursor(img, hover=True)
cursor.connect('add', show_rect)
plt.show()
推荐阅读
- spring - Spring Framework:为什么命令行参数“--argument-name =”抛出无效的参数语法?
- ios - 在某个位置画一个十字以及节点旋转的工作原理
- c# - 如何创建具有类限制的属性
- python - 在 Python 中处理错误的值
- mysql - MySQL - 无法在总和为零的情况下获得每日总和,已经使用日历表
- linux - Linux 上是否有 sprintf_l 等价物?
- java - 使用 Netbeans 表单时出现一般“链接错误”
- reactjs - 如何向 Material-UI 组件添加自定义变体(React / Typescript)
- git - 尝试使用 Git add 不起作用:权限被拒绝
- sql - 教义和自定义 Oracle REGEXP_LIKE