如何用Python的Matplotlib等库绘制字典格式的24x4二维网格数据
问题描述
需要绘制一个24×4的二维网格,每个网格坐标对应一个数值,数据存储为如下格式的字典:
{ 'map1_ID': [ ['x_coor','y_coor','data_to plot'], ['x_coor','y_coor','data_to plot'], ... ], 'map2_ID': [ ['x_coor','y_coor','data_to plot'], ['x_coor','y_coor','data_to plot'], ... ] }
使用Matplotlib实现方案
步骤1:数据预处理
先把字典中的列表数据转换为匹配24×4网格的二维数组,未提供数据的位置可以用NaN(空白)或0填充。
步骤2:绘制网格可视化
用Matplotlib的imshow绘制热力图,配合网格线和数值标注,清晰展示每个单元格的数值。
完整代码示例
import matplotlib.pyplot as plt import numpy as np # 模拟用户提供的字典数据 grid_data = { 'map1_ID': [ ['0', '0', 10], ['1', '0', 15], ['23', '0', 5], ['0', '3', 20], ['12', '2', 8], ['23', '3', 12] ], 'map2_ID': [ ['0', '0', 5], ['5', '1', 18], ['23', '3', 25], ['10', '2', 7], ['15', '1', 14] ] } def prepare_grid(map_data, grid_size=(24, 4)): # 初始化网格,未填充位置用NaN表示 grid = np.full(grid_size, np.nan) for x_str, y_str, value in map_data: x = int(x_str) y = int(y_str) # 注意:y对应行索引,x对应列索引,根据实际坐标逻辑调整 grid[y][x] = value return grid # 绘制单个网格图 plt.figure(figsize=(12, 3)) map1_grid = prepare_grid(grid_data['map1_ID']) plt.imshow(map1_grid, cmap='viridis', aspect='auto', extent=[0, 24, 4, 0]) # 为每个有数据的单元格添加数值标注 for y in range(4): for x in range(24): if not np.isnan(map1_grid[y][x]): plt.text(x + 0.5, y + 0.5, int(map1_grid[y][x]), ha='center', va='center', color='white') plt.xlabel('X坐标') plt.ylabel('Y坐标') plt.title('map1_ID 网格数据可视化') plt.colorbar(label='数据值') plt.xticks(np.arange(0, 24, 1)) plt.yticks(np.arange(0, 4, 1)) plt.grid(which='both', color='black', linewidth=0.5) plt.show() # 绘制多图对比(map1和map2) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 3)) # 处理并绘制map1 map1_grid = prepare_grid(grid_data['map1_ID']) im1 = ax1.imshow(map1_grid, cmap='viridis', aspect='auto', extent=[0, 24, 4, 0]) for y in range(4): for x in range(24): if not np.isnan(map1_grid[y][x]): ax1.text(x + 0.5, y + 0.5, int(map1_grid[y][x]), ha='center', va='center', color='white') ax1.set_xlabel('X坐标') ax1.set_ylabel('Y坐标') ax1.set_title('map1_ID 网格数据') ax1.set_xticks(np.arange(0, 24, 1)) ax1.set_yticks(np.arange(0, 4, 1)) ax1.grid(which='both', color='black', linewidth=0.5) # 处理并绘制map2 map2_grid = prepare_grid(grid_data['map2_ID']) im2 = ax2.imshow(map2_grid, cmap='viridis', aspect='auto', extent=[0, 24, 4, 0]) for y in range(4): for x in range(24): if not np.isnan(map2_grid[y][x]): ax2.text(x + 0.5, y + 0.5, int(map2_grid[y][x]), ha='center', va='center', color='white') ax2.set_xlabel('X坐标') ax2.set_ylabel('Y坐标') ax2.set_title('map2_ID 网格数据') ax2.set_xticks(np.arange(0, 24, 1)) ax2.set_yticks(np.arange(0, 4, 1)) ax2.grid(which='both', color='black', linewidth=0.5) # 添加统一颜色条 fig.colorbar(im1, ax=[ax1, ax2], label='数据值') plt.tight_layout() plt.show()
关键说明
- 坐标对应:如果你的X/Y坐标与行/列的对应关系不同,调整
grid[y][x]为grid[x][y]即可 - 空白填充:若需要未提供数据的位置显示0,把
np.full(grid_size, np.nan)改为np.zeros(grid_size) - 颜色自定义:更换
cmap参数可调整颜色风格,比如'coolwarm'、'plasma'等 - 网格线:通过
plt.grid添加单元格边框,确保网格结构清晰
内容的提问来源于stack exchange,提问作者Travis Batista
相关产品推荐
相关产品推荐

