使用python库绘制混淆矩阵(数字不居中,精度显示问题的解决)

在写小论文期间需要绘制混淆矩阵,通过查阅资料解决了如下的问题。

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()

输出图像:
在这里插入图片描述

  • 7
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值