首页 > 解决方案 > Jupyter notebook 在(imshow)图上移动矩形

问题描述

我绘制一个 nd 数组,并在一个固定点显示一个矩形。但是我希望能够移动矩形(当我移动鼠标时),并显示一些东西(根据鼠标/矩形的坐标)。有没有办法在 Jupyter 笔记本中实现这样的事情?

标签: pythonmatplotlibjupyter-notebookdata-visualization

解决方案


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()

示例图


推荐阅读