python - 如何使用字典中的值注释网格图
问题描述
我有这个 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 是左下角而不是右上角)。我想要的是在网格本身中显示每个单元格索引的关联键值对(比如拿一支笔并在适当的单元格中写入值,除非以编程方式)。
显然它可能会有点拥挤,在这种情况下,我可以让网格本身更大。但是有没有办法在每个相应的单元格上将字典中的文本显示到网格上?
解决方案
(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.text
matplotlib.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')
推荐阅读
- ruby-on-rails - NoMethodError (undefined method `[]' for nil:NilClass): Ruby on Rails 即使使用 dig
- c - 这个带有两个递归调用的返回语句是如何工作的?
- c - 无法理解如何设置位
- javascript - 为什么只是通过?我想知道更多我需要解释
- node.js - NPM 安装失败了几个 ENOENT
- java - 在一个 Kafka Topic 下发送两个 Serialized Java 对象
- r - 关键字搜索字符串
- node.js - ?retryWrites=true&w=majority 连接 Node.js 应用到 MongoDB Atlas 上的集群时的含义
- python - numpy中的错误ifft
- ios - 如何在 iOS 设备和键盘之间直接发送/接收 AudioKit MIDI 消息?