【发布时间】:2014-08-03 03:49:44
【问题描述】:
我想使用 matplotlib 创建混淆矩阵的可视化。 下面显示的方法的参数是类标签(字母), 分类结果为列表列表 (conf_arr) 和输出文件名。 到目前为止,我对结果感到非常满意,还有最后一个问题:
我无法在网格线之间将轴刻度标签居中。 如果我将 extent 参数传递给 imshow 方法,如下所示, 网格按照我的意愿对齐。 如果我将其注释掉,则网格未对齐,但标签是我想要的 他们是。 我想我需要一种方法来在关联的刻度和下一个刻度之间移动刻度标签 但我不知道这是否以及如何实现。
总而言之,我想要左图中的网格/刻度,但是刻度标签 如右图所示:
def create_confusion_matrix(alphabet, conf_arr, outputname):
norm_conf = []
width = len(conf_arr)
height = len(conf_arr[0])
for i in conf_arr:
a = 0
tmp_arr = []
a = sum(i, 0)
for j in i:
tmp_arr.append(float(j)/float(a))
norm_conf.append(tmp_arr)
fig = plt.figure(figsize=(14,14))
#fig = plt.figure()
plt.clf()
ax = fig.add_subplot(111)
ax.set_aspect(1)
ax.grid(which='major')
res = ax.imshow(np.array(norm_conf), cmap=plt.cm.binary,
interpolation='none', aspect='1', vmax=1,
##Commenting out this line sets labels correctly,
##but the grid is off
extent=[0, width, height, 0]
)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.2)
cb = fig.colorbar(res, cax=cax)
#Axes
ax.set_xticks(range(width))
ax.set_xticklabels(alphabet, rotation='vertical')
ax.xaxis.labelpad = 0.5
ax.set_yticks(range(height))
ax.set_yticklabels(alphabet, rotation='horizontal')
#plt.tight_layout()
plt.savefig(outputname, format='png')
生成的图像如下所示:
【问题讨论】:
-
this question 中的解决方案对您有用吗?
-
这是一个写得很清楚,措辞得当的问题! (+1) 不知道你为什么被否决。
标签: python matplotlib