我想通过 plt.subplots 创建多个 imshow。每个 imshow 的轴应该用字符串标记,而不是数字(这些是表示类别之间相关性的相关矩阵)。
我从 documentation 中得出结论(非常底部),plt.yticks()
返回我想要的,但我似乎无法设置它们。 ax.yticks(...)
也不起作用。
我找到了 docs about the ticker locator and formatter但我不确定这是否或如何有用
A = np.random.random((3,3))
B = np.random.random((3,3))+1
C = np.random.random((3,3))+2
D = np.random.random((3,3))+3
lbls = ['la', 'le', 'li']
fig, axar = plt.subplots(2,2)
fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
ar_plts = [A, B, C, D]
for i,ax in enumerate(axar.flat):
im = ax.imshow(ar_plts[i]
, interpolation='nearest'
, origin='lower')
ax.grid(False)
plt.yticks(np.arange(len(lbls)), lbls)
fig.colorbar(im, cax=cbar_ax)
fig_path = r"blah/blub"
fig_name = "matrices.png"
fig_fobj = os.path.join(fig_path, fig_name)
fig.savefig(fig_fobj)
最佳答案
您可以使用 plt.xticks
或 ax.set_xticks
更改数字(y 相同)但这不允许您更改刻度的标签.为此,您需要 ax.set_xticklabels
(y 也一样)。
这段代码对我有用
A = np.random.random((3,3))
B = np.random.random((3,3))+1
C = np.random.random((3,3))+2
D = np.random.random((3,3))+3
lbls = ['la', 'le', 'li']
fig, axar = plt.subplots(2,2)
fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
ar_plts = [A, B, C, D]
for i,ax in enumerate(axar.flat):
im = ax.imshow(ar_plts[i]
, interpolation='nearest'
, origin='lower')
ax.grid(False)
ax.set_yticks([0,1,2])
ax.set_xticks([0,1,2])
ax.set_xticklabels(lbls)
ax.set_yticklabels(lbls)
fig.colorbar(im, cax=cbar_ax)
fig_path = r"blah/blub"
fig_name = "matrices.png"
fig_fobj = os.path.join(fig_path, fig_name)
fig.savefig(fig_fobj)
您需要小心处理多个图的颜色条。它仅为您的最后一个图提供正确的值。如果它对于您需要使用的所有地 block 都是正确的
im = ax.imshow(ar_plts[i],
interpolation='nearest',
origin='lower',
vmin=0.0,vmax=1.0)
我假设您数据中的最小值是 0.0
,最大的是 1.0
。
关于python - 用字符串标记 matplotlib imshow 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28762105/