我要映射的数据是形状为5x64的矩阵,称为“ field_matrix”
field_matrix = [
[0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 2 2 2 2 2 2 2 2 2 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1]
[0 0 0 0 0 0 0 1 0 0 1 2 2 2 2 2 2 2 2 2 0 0 2 2 2 2 2 2 0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 2 2 2 2 2 2 2 2 2 0 2 2 2 2 2 2 2 0 0 0 0]
[0 0 0 0 0 0 0 1 0 1 0 2 2 2 2 2 2 2 2 2 0 2 2 2 2 2 2 2 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 2 2 2 2 2 2 2 1 1 1 1 1]
[0 0 0 0 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0
2 2 2 2 2 2 2 0 0 0 0 1 0 1 1 0 0 0 0 1 1 1 1 1 1 1 1]
[0 0 0 0 1 1 1 1 1 1 1 2 2 2 2 2 2 2 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0
0 0 0 0 0 0 0 0 0 0 1 2 2 2 2 0 1 1 1 0 0 1 1 1 1 1 1]]
代码是:
norm = mpl.colors.Normalize(vmin=0, vmax=3)
cmap = cm.Blues
mapper = cm.ScalarMappable(norm=norm, cmap=cmap)
#field_value_dict = {0: 'Sensor', 1: 'Multi-Value', 2: 'Constant', 3: 'Counter'}
field_value_dict = {2: 'Sensor', 1: 'Multi-Value', 0: 'Constant', 3: 'Counter'}
patch_list = []
for k,v in field_value_dict.items():
patch = mpatches.Patch(color=mapper.to_rgba(k), label=v)
patch_list.append(patch)
#print(patch_list)
plt.figure(figsize=(20, 12.5))
plt.imshow(field_matrix, interpolation='nearest', cmap=cmap, )
ax = plt.gca()
# Put a legend to the right of the current axis
# Shrink current axis by 20%
#box = ax.get_position()
#ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
#ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), handles=patch_list)
ax.legend(loc='center', bbox_to_anchor=(0.5, -0.5), handles=patch_list)
# Set the ticks and labels
plt.yticks(np.arange(5), [utilities.num2pid[k] for k in range(5)]) #num2pids will output '0000', 'F002', 'F003', 'F004', 'F005 -- but note that '0000' is missing from the image
plt.xticks(np.arange(-0.5, 60, 8.), np.arange(0, 64, 8))
# Set offset ticks to make the grid boxes surround the squares representing bits
ax.set_xticks(np.arange(-0.5, 64.5, 8.), minor=True)
ax.set_yticks(np.arange(0.5, 20.5, 1.), minor=True)
plt.grid(which='minor')
plt.xlabel('bit')
plt.ylabel('ID')
fig_save_dir = os.path.expanduser('../figures/')
#filename = os.path.join(fig_save_dir, 'field_map.pgf')
filename = os.path.join(fig_save_dir, 'field_map_J1939-PGNs.png')
plt.savefig(filename)#, bbox_inches=2)
plt.show()
问题: 数据矩阵(field_matrix)中的每个向量(总计5个)的值为0-3,并且该值产生适当的颜色-请参见下图和图例。
但是,当输出图像还应包含0000时,它仅产生4行(F002,F003,F004,F005),因为该绘图图形中应该有5行数据。
我试图在Stack上使用类似的imshow()问题进行故障排除,但无法解决该问题。有什么想法吗?
除了问题-作为matplotlib的新手,您是否知道如何消除图形中的空白(请注意图像是如何倾斜到图形顶部的。
谢谢!
答案 0 :(得分:0)
基本上,您正在这样做:
plt.yticks(np.arange(5), [utilities.num2pid[k] for k in range(5)]) #num2pids will output '0000', 'F002', 'F003', 'F004', 'F005 -- but note that '0000' is missing from the image
然后:
ax.set_yticks(np.arange(0.5, 20.5, 1.), minor=True)
因此,第二行覆盖同一轴上之前修改过的yticks
。所以...我删除了第二行并执行了以下操作:
plt.yticks(np.arange(0, 5), ['0000', 'F002', 'F003', 'F004', 'F005'])
注意,我使用了一个固定列表,其中包含utilities.num2pid[k]
所期望的值。因为我不知道该功能。
我得到了这个结果:
希望这会有所帮助。