如何使用matplotlib将存储整数的字典转换为热力图
实现方案
你只需要先把字符串坐标为键的字典转换成二维numpy数组,再调用matplotlib的imshow方法即可,注意匹配你定义的(0,0)在左上角的坐标规则即可。
具体步骤
- 解析字典的所有键,拆分出x、y坐标,计算网格的宽、高维度
- 初始化对应尺寸的二维数组,遍历字典将值填充到数组对应的坐标位置
- 调用绘图接口生成热力图,可按需添加色条、单元格数值标注、调整配色
完整代码
import matplotlib.pyplot as plt import numpy as np # 示例字典数据 grid = { '0,0': 1, # top left '1,0': 4, # top right '0,1': 3, # bottom left '1,1': 2 # bottom right } # 字典转二维网格数组 x_list, y_list = [], [] for pos in grid.keys(): x, y = map(int, pos.split(',')) x_list.append(x) y_list.append(y) grid_w, grid_h = max(x_list) + 1, max(y_list) + 1 grid_arr = np.zeros((grid_h, grid_w)) for pos, val in grid.items(): x, y = map(int, pos.split(',')) grid_arr[y, x] = val # 绘制热力图 fig, ax = plt.subplots() heatmap = ax.imshow(grid_arr, cmap='viridis', origin='upper') # 添加颜色条 plt.colorbar(heatmap) # 标注每个单元格的数值 for y in range(grid_h): for x in range(grid_w): ax.text(x, y, grid_arr[y, x], ha='center', va='center', color='white') # 设置坐标轴刻度对齐单元格 ax.set_xticks(np.arange(grid_w)) ax.set_yticks(np.arange(grid_h)) plt.show()
效果说明
运行代码后生成的热力图完全匹配你给出的位置规则:左上角值为1、右上角值为4、左下角值为3、右下角值为2。如果需要调整配色,修改imshow的cmap参数即可,常用的可选值有Blues、Reds、coolwarm等。
内容的提问来源于stack exchange,提问作者mr.hooman
相关产品推荐
相关产品推荐

