How to mark cells in matplotlib.pyplot.imshow (drawing cell borders)

ⅰ亾dé卋堺 提交于 2021-02-08 04:08:13

问题


I have a small 2d vector to display:

import matplotlib.pyplot as plt
import numpy as np

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

As folllow:

But now I want to mark a specific cell, in order to focus the reader on that cell. Because this is of specific interest...

Therefore something like a border of this cell would be nice:

Does someone know how to archive this with matplotlib in a convenient way?


回答1:


Put a rectangle at the position of the pixel you want to highlight.

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



来源:https://stackoverflow.com/questions/56654952/how-to-mark-cells-in-matplotlib-pyplot-imshow-drawing-cell-borders

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!