用字符串标记 matplotlib imshow 轴

label matplotlib imshow axes with strings

我想通过 plt.subplots 创建多个 imshow。每个 imshow 的轴应该用字符串标记,而不是数字(这些是表示类别之间相关性的相关矩阵)。

我从documentation(最底层)想出来了,那个plt.yticks() returns是我想要的,但是我好像不能设置它们。 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.xticksax.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)

您需要注意多个绘图的颜色条。它仅为您的最后一个图提供正确的值。如果它对您需要使用的所有地块都是正确的

im = ax.imshow(ar_plts[i],
             interpolation='nearest',
             origin='lower',
             vmin=0.0,vmax=1.0)

我假设你数据中的最小值是 0.0,最大的是 1.0