matplotlib中图像中标签的问题

时间:2014-12-30 05:24:48

标签: python image matplotlib labels

我必须在图像中显示带有相应标签的混淆矩阵。我正在使用matplotlib。但是,在创建图像时,它仅显示替代标签,并且不显示所有标签。矩阵中的数据也与其他网格数据重叠。应该感谢你的帮助。

labels_x = ['D','F','A','G','DG','R','I','BS','COA','W','T','UserAcc%'] #create labels  for each classes
labels_y = ['D','F','A','G','DG','R','I','BS','COA','W','T','ProdAcc%']
# Guassian Confusion Matrix plo
fig = plt.figure(figsize=(18, 18))
ax = fig.add_subplot(111)
cax = ax.matshow(cm1 )

pl.title('CONFUSION MATRIX(Guassian)')
for i,j in ((x,y) for x in xrange(len(cm1))
        for y in xrange(len(cm1[0]))):
    ax.annotate(str(cm1[j][i]),xy=(i,j))
fig.colorbar(cax)
ax.set_xticklabels(['']+labels_x)
ax.set_yticklabels(['']+labels_y)
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.set_cmap('Pastel1')
plt.savefig(finaldata_path_plot+"GuassianConfusionMatrix.pdf", format ='pdf')
plt.show()
plt.close()

Confusion matrix image with alternate labels and overlapped data

1 个答案:

答案 0 :(得分:3)

默认情况下,matplotlib会自动选择"甚至"间隔。刻度标签仅出现在刻度位置,因此如果您想标记每个列和行,您需要设置刻度位置和刻度标签。

基本上,你需要这样的东西:

i = range(len(labels))
ax.set(xticks=i, xticklabels=labels, yticks=i, yticklabels=labels)

作为一个完整的例子:

import numpy as np
import matplotlib.pyplot as plt

labels = ['D', 'F', 'A', 'G', 'DG', 'R', 'I', 'BS', 'COA', 'W', 'T']
data = np.random.random((len(labels), len(labels)))

fig, ax = plt.subplots()
im = ax.matshow(data, cmap='Pastel1')
fig.colorbar(im)

i = range(len(labels))
ax.set(xticks=i, xticklabels=labels, yticks=i, yticklabels=labels)

for (i, j), z in np.ndenumerate(data):
    ax.text(j, i, '{:0.1f}'.format(z), ha='center', va='center')

ax.set(ylabel='True label', xlabel='Predicted label', title='Confusion Matrix')
plt.show()

enter image description here