使用plt.imshow绘制RGB纯色方块时数量不符,如何修复?
问题原因
你的rgb_values是**(3,3)的二维数组**,plt.imshow默认会将其识别为3行3列的单通道灰度图,因此渲染出9个色块。要显示3个独立的RGB纯色块,需要调整数组形状以符合RGB图像的格式要求:(高度, 宽度, 通道数),同时确保RGB值处于matplotlib支持的范围(0-1浮点数或0-255整数,推荐归一化到0-1)。
修复方案
方案1:调整数组形状快速实现
通过reshape将数组转为(1, 3, 3)的形状(1行,3个色块,每个色块3个RGB通道),再传入plt.imshow:
import matplotlib.pyplot as plt import numpy as np rgb_values = np.array([[47, 32, 31], [14, 10, 12], [119, 122, 141]]) # 调整形状并归一化到0-1范围 rgb_reshaped = rgb_values.reshape(1, 3, 3) / 255.0 plt.imshow(rgb_reshaped) # 优化显示:自定义刻度并隐藏y轴刻度 plt.xticks([0, 1, 2], ['色块1', '色块2', '色块3']) plt.yticks([]) plt.show()
方案2:用矩形补丁自定义绘制(更灵活)
如果需要更灵活地控制色块大小、位置或添加额外元素,可以使用matplotlib.patches.Rectangle绘制每个色块:
import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Rectangle rgb_values = np.array([[47, 32, 31], [14, 10, 12], [119, 122, 141]]) # 归一化RGB值到0-1范围 colors = rgb_values / 255.0 fig, ax = plt.subplots() # 设置坐标轴范围 ax.set_xlim(0, len(colors)) ax.set_ylim(0, 1) # 逐个绘制色块 for idx, color in enumerate(colors): # 绘制从x=idx到x=idx+1,y=0到y=1的矩形 rect = Rectangle((idx, 0), 1, 1, color=color) ax.add_patch(rect) # 设置刻度标签 plt.xticks([idx + 0.5 for idx in range(len(colors))], ['色块1', '色块2', '色块3']) plt.yticks([]) plt.show()
内容的提问来源于stack exchange,提问作者albusdemens
相关产品推荐
相关产品推荐

