如何在Python的Matplotlib中为每个1×1像素添加边框并标注数值
问题描述
我使用Python的Matplotlib编写了以下代码生成图像,现咨询如何为每个1×1像素添加边框,以及如何添加数组中对应的像素网格编号?
import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() ax.set_title('Satellite 1') grid=np.array( [ [ 1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,], [ 9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,], [ 17,17,18,18,19,19,20,0,21,21,22,0,23,23,24,24,], [ 25,25,26,26,27,27,28,28,29,29,30,30,31,31,32,32,], [ 33,33,34,0,35,35,36,36,37,37,0,38,39,39,40,40,], [ 41,41,41,42,42,42,43,43,43,44,44,44,45,45,45,0,], ] ) #ax.imshow(grid) im = plt.imshow(grid, cmap='PuBuGn') # Move left and bottom spines outward by 10 points ax.spines['left'].set_position(('outward', 10)) ax.spines['bottom'].set_position(('outward', 10)) # Hide the right and top spines ax.spines['right'].set_visible(True) ax.spines['top'].set_visible(True) # Only show ticks on the left and bottom spines ax.yaxis.set_ticks_position('left') ax.xaxis.set_ticks_position('bottom') im.axes.get_xaxis().set_visible(True) im.axes.get_yaxis().set_visible(True) ax.set_frame_on(True) ax.set_aspect('equal') plt.colorbar(orientation='horizontal') plt.show()
解决方案
1. 为每个像素添加边框
利用Matplotlib的网格线功能,将网格线对齐到像素边缘即可实现边框效果,核心是调整刻度与网格的位置匹配:
- 设置x、y轴刻度为像素中心位置
- 开启网格线并设置样式,让网格线刚好落在像素边界
- 隐藏刻度线避免视觉干扰
2. 添加像素网格编号
遍历数组每个元素,在对应像素中心位置添加文本标注,可按需跳过值为0的元素:
- 双重循环遍历数组的行与列
- 使用
ax.text()在像素中心写入对应编号,设置居中对齐与字体样式
完整修改代码
import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() ax.set_title('Satellite 1') grid=np.array( [ [1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,], [9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,], [17,17,18,18,19,19,20,0,21,21,22,0,23,23,24,24,], [25,25,26,26,27,27,28,28,29,29,30,30,31,31,32,32,], [33,33,34,0,35,35,36,36,37,37,0,38,39,39,40,40,], [41,41,41,42,42,42,43,43,43,44,44,44,45,45,45,0,], ] ) # 绘制基础图像 im = plt.imshow(grid, cmap='PuBuGn') # --- 添加像素边框 --- ax.set_xticks(np.arange(grid.shape[1])) ax.set_yticks(np.arange(grid.shape[0])) ax.grid(color='black', linestyle='-', linewidth=0.5) ax.tick_params(axis='both', which='both', length=0, labelleft=True, labelbottom=True) # --- 添加网格编号 --- for i in range(grid.shape[0]): for j in range(grid.shape[1]): val = grid[i, j] if val != 0: ax.text(j, i, str(val), ha='center', va='center', color='white', fontsize=8) # 保留原有轴样式设置 ax.spines['left'].set_position(('outward', 10)) ax.spines['bottom'].set_position(('outward', 10)) ax.spines['right'].set_visible(True) ax.spines['top'].set_visible(True) ax.yaxis.set_ticks_position('left') ax.xaxis.set_ticks_position('bottom') ax.set_aspect('equal') plt.colorbar(orientation='horizontal') plt.show()
关键说明
- 边框实现:网格线通过刻度位置对齐,刚好覆盖每个像素的边缘,形成1×1的边框效果
- 编号添加:
ax.text(j, i, ...)中,j对应列索引(x坐标)、i对应行索引(y坐标),ha和va参数确保文本在像素内居中,可根据需求调整字体大小、颜色
内容的提问来源于stack exchange,提问作者MO MO MA
相关产品推荐
相关产品推荐

