You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Matplotlib网格图的对应单元格中标注字典存储的数值

Matplotlib网格单元格文本标注实现方案

实现思路

  1. 先根据单元格编号规则,将索引转换为对应单元格的中心坐标:你的网格是3列×3行,按列纵向编号,因此列索引 = 单元格序号 // 3,行索引 = 单元格序号 % 3,单元格中心坐标为x = 列索引 + 0.5,y = 行索引 + 0.5,匹配你设置的倒置y轴规则。
  2. 为了避免文本拥挤,将四个方向的数值分别标注在单元格的对应方位,无需换行也不会重叠。
  3. 可通过调整画布尺寸、字体大小进一步优化显示效果。

完整可运行代码

import numpy as np
import matplotlib.pyplot as plt

# 调大画布尺寸避免内容拥挤
fig, ax = plt.subplots(figsize=(8, 8))
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}
             }

# 遍历字典标注文本
for idx, info in dictionary.items():
    col = idx // 3
    row = idx % 3
    center_x = col + 0.5
    center_y = row + 0.5
    
    # 四个方向数值分别标注在对应方位
    ax.text(center_x, center_y - 0.3, f"up:{info['up']}", ha='center', va='top', fontsize=10)
    ax.text(center_x, center_y + 0.3, f"down:{info['down']}", ha='center', va='bottom', fontsize=10)
    ax.text(center_x - 0.4, center_y, f"left:{info['left']}", ha='right', va='center', fontsize=10)
    ax.text(center_x + 0.4, center_y, f"right:{info['right']}", ha='left', va='center', fontsize=10)

plt.show()

效果调整说明

  • 如果觉得内容仍拥挤,可继续调大figsize参数的数值,比如改成(10,10)
  • 字体大小可通过修改fontsize参数调整
  • 如果希望把所有文本集中在单元格中心,可将内容拼接为换行字符串,示例:ax.text(center_x, center_y, f"up:{info['up']}\ndown:{info['down']}\nleft:{info['left']}\nright:{info['right']}", ha='center', va='center')

内容的提问来源于stack exchange,提问作者AI92

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 11:15:07