用字符串标记Matplotlib imshow坐标轴

5
我想通过plt.subplots创建多个imshows。 每个imshow的轴都应该用字符串标记,而不是数字(这些数字表示类别之间的相关性矩阵)。
我从文档中找到了文档(非常底部),发现plt.yticks()可以返回我想要的内容,但我似乎无法设置它们。另外,ax.yticks(...)也无效。
我在有关刻度定位器和格式化程序的文档中找到了信息,但我不确定如何使用它们。
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)
1个回答

8
你可以使用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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接