带有网格注释的热图

Heatmap with gridlike annotation

我有以下情节

import numpy as np
import matplotlib.pyplot as plt

a = np.random.randn(4,4)
fig, ax = plt.subplots()
im = ax.imshow(a)
plt.axis('off')
plt.show()

输出:

我正在尝试添加以下网格线:

gridlines = np.array([
  [0,2], [2,4],
  [0,4],
  [0,3], [3,4],
  [0,1], [1,3],
])

这样情节看起来像这样:

最后,我想在每个红色矩形的中心添加文本:

是否有使用 matplotlib 执行此操作的任何文档或教程?

由于您已经定义了 gridlines,因此通过添加 Rectangle 和文本注释很容易实现该结果。

请注意,在下文中我已将 gridlines 修改为字典,将每个“行”映射到网格。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

gridlines = {
  0: [[0,2], [2,4]],
  1: [[0,4]],
  2: [[0,3], [3,4]],
  3: [[0,1], [1,3]],
}

a = np.random.randn(4,4)
fig, ax = plt.subplots()
im = ax.imshow(a)
plt.axis('off')

xmin, xmax = ax.get_xlim()
ymin, ymax = ax.get_ylim()
dx = (xmax - xmin) / 4
dy = (ymax - ymin) / 4

count = 1
for r, v in gridlines.items():
    for (_xmin, _xmax) in v:
        x = xmin + dx * _xmin
        y = ymax - (r + 1) * dy
        w = dx * (_xmax - _xmin)
        ax.add_patch(Rectangle((x, y), w, dy, facecolor='none', edgecolor="r", linewidth=3))
        ax.text(x + w / 2, ymax - (r + 1) * dy + dy / 2, "text%s" % count, ha="center", va="center", color="white")
        count += 1
    
plt.show()