用字符串标记matplotlib imshow轴

2024-05-03 07:19:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想通过plt.subblots创建多个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)

Tags: pathnpfigpltrandomaxarimshow
1条回答
网友
1楼 · 发布于 2024-05-03 07:19:57

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

相关问题 更多 >