如何在matplotlib.pyplot.imshow中标记单元格(绘制单元格边框)

时间:2019-06-18 18:23:09

标签: python matplotlib

我有一个小的二维矢量要显示:

import matplotlib.pyplot as plt
import numpy as np

img = np.random.rand(4,10)
plt.imshow(img, cmap='Reds')

如下:

enter image description here

但是现在我要标记一个特定的单元格,以便使读者将注意力集中在该单元格上。因为这特别有意义...

因此,像该单元格的边框这样的东西会很好:

enter image description here

有人知道如何以方便的方式使用matplotlib将其存档吗?

1 个答案:

答案 0 :(得分:2)

在要突出显示的像素位置放置一个矩形。

import matplotlib.pyplot as plt
import numpy as np

def highlight_cell(x,y, ax=None, **kwargs):
    rect = plt.Rectangle((x-.5, y-.5), 1,1, fill=False, **kwargs)
    ax = ax or plt.gca()
    ax.add_patch(rect)
    return rect

img = np.random.rand(4,10)
plt.imshow(img, cmap='Reds')

highlight_cell(2,1, color="limegreen", linewidth=3)

plt.show()

enter image description here

相关问题