首页 > 解决方案 > 如何使用字典中的值注释网格图

问题描述

我有这个 Matplotlib 网格,想在每个网格单元格中写入文本。文本由字典提供。我该怎么做?

这是我到目前为止所拥有的:

fig, ax = plt.subplots()
plt.xlim(0, 3)
plt.ylim(3, 0)
plt.grid(True)
plt.xticks(np.arange(0, 4, 1.0))
plt.yticks(np.arange(0, 4, 1.0))

dictionary = {0: {'down': 58, 'right': 43, 'up': 9, 'left': 2},
              1: {'down': 23, 'right': 35, 'up': 1, 'left': 1},
              2: {'down': 4,  'right': 23, 'up': 0, 'left': 1},
              3: {'down': 21, 'right': 24, 'up': 1, 'left': 0},
              4: {'down': 24, 'right': 31, 'up': 2, 'left': 1},
              5: {'down': 6,  'right': 46, 'up': 1, 'left': 0},
              6: {'down': 25, 'right': 2, 'up': 1,  'left': 0 },
              7: {'down': 54, 'right': 4, 'up': 1,  'left': 1},
              8: {'down': 0,  'right': 0, 'up': 0,  'left': 0}
             }

网格如下所示:

在此处输入图像描述

网格单元标记为 0 到 8,按列垂直排列(单元 2 是左下角而不是右上角)。我想要的是在网格本身中显示每个单元格索引的关联键值对(比如拿一支笔并在适当的单元格中写入值,除非以编程方式)。

显然它可能会有点拥挤,在这种情况下,我可以让网格本身更大。但是有没有办法在每个相应的单元格上将字典中的文本显示到网格上?

标签: pythondictionarymatplotlibannotations

解决方案


  • (x, y)使用列表推导为注释 的位置创建一个元组列表。
    • 向下和横跨:[(x + 0.05, y + 0.5) for x in range(3) for y in range(3)]
    • 横向和向下:[(x + 0.05, y + 0.5) for y in range(3) for x in range(3)]
  • zip值的位置,并使用或dict添加文本matplotlib.pyplot.textmatplotlib.axes.Axes.text
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(12, 4))
ax.set_xlim(0, 3)
ax.set_ylim(3, 0)
ax.grid(True)
ax.set_xticks(np.arange(0, 4, 1.0))
ax.set_yticks(np.arange(0, 4, 1.0))

dictionary = {0: {'down': 58, 'right': 43, 'up': 9, 'left': 2},
              1: {'down': 23, 'right': 35, 'up': 1, 'left': 1},
              2: {'down': 4,  'right': 23, 'up': 0, 'left': 1},
              3: {'down': 21, 'right': 24, 'up': 1, 'left': 0},
              4: {'down': 24, 'right': 31, 'up': 2, 'left': 1},
              5: {'down': 6,  'right': 46, 'up': 1, 'left': 0},
              6: {'down': 25, 'right': 2, 'up': 1,  'left': 0},
              7: {'down': 54, 'right': 4, 'up': 1,  'left': 1},
              8: {'down': 0,  'right': 0, 'up': 0,  'left': 0}}

# create tuples of positions
positions = [(x + 0.05, y + 0.5) for x in range(3) for y in range(3)]

# add text
for (x, y), (k, v) in zip(positions, dictionary.items()):
    ax.text(x, y, f'{k}: {v}', color='purple')

在此处输入图像描述


推荐阅读