在写小论文期间需要绘制混淆矩阵,通过查阅资料解决了如下的问题。
1)混淆矩阵中数字不居中
解决方法:设置plt.text中的va和ha参数为’center’
plt.text(first_index, second_index, int(confusion[first_index][second_index]), va='center',
ha='center',
fontsize=13.5)
2)混淆矩阵中数字显示的精度不同
如图:
通过查看代码发现,创建的np数组中数字的格式为:
<class ‘numpy.float64’>
所以出现上述情况,因此可以通过如下代码解决:
temp = confusion[first_index][second_index]
//如果是0.0或者是100.0,只保留整数部分
if temp == 0.0 or temp == 100.0:
plt.text(first_index, second_index, int(temp), va='center',
ha='center',
fontsize=13.5)
else:
//否则保留小数点后2位,当然可以自由设置精度
plt.text(first_index, second_index, r'{0:.2f}'.format(temp), va='center',
ha='center',
fontsize=13.5)
综上,总代码如下:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
//设置字体
plt.rc('font', family='Times New Roman')
del matplotlib.font_manager.weight_dict['roman']
plt.rcParams['xtick.direction'] = 'in'
plt.rcParams['ytick.direction'] = 'in'
confusion = np.array(([96.15, 0, 3.76, 0], [0, 100, 0, 0], [3.85, 0, 95.24, 0], [0, 0, 0, 100]))
indices = range(len(confusion))
plt.xticks(indices, [0, 1, 2, 3], fontsize=13.5)
plt.yticks(indices, [0, 1, 2, 3], fontsize=13.5)
for first_index in range(len(confusion)): # 第几行
for second_index in range(len(confusion[first_index])): # 第几列
temp = confusion[first_index][second_index]
if temp == 0.0 or temp == 100.0:
plt.text(first_index, second_index, int(temp), va='center',
ha='center',
fontsize=13.5)
else:
plt.text(first_index, second_index, r'{0:.2f}'.format(temp), va='center',
ha='center',
fontsize=13.5)
plt.imshow(confusion, interpolation='nearest', cmap=plt.cm.Blues)
cb = plt.colorbar()
//设置colorbar的字号
cb.ax.tick_params(labelsize=13.5)
plt.savefig('matrix.png', dpi=300)
plt.show()
输出图像: