你好 :) 有人知道如何使 matplotlib 矩阵图可点击吗?
例如,如果我单击矩阵的一个单元格,它应该突出显示该单元格的行和列(参见下面的前后图片,单击此单元格中间的单元格后,相应行和列的背景变为绿色例子)。该图在导出后应该是可点击的(例如,我们可以在导入 pdf 时点击它),但在 jupyter notebook 中显示时则不一定。
这是我用来绘制混淆矩阵的代码:
def plotConfusionMatrix(y_test,y_pred,list_name_classes,ax=None):
'''
Plot row normed confusion matrix. Rows are normalized to sum to 100% throughout true classes. The number of observations is also visible on the matrix
Parameters
----------
y_test : list or array
true encoded labels
y_pred : list or array
predicted encded labels
list_name_classes : list or array of str
names of the classified classes. Must be in the same order as encoded labels
Returns
-------
matplotlib axis
'''
if ax is None:
ax=plt.gca()
cf_matrix = confusion_matrix(y_test, y_pred)
matrix_percent=[]
for row in range(cf_matrix.shape[0]):
matrix_percent.append(cf_matrix[row]/sum(cf_matrix[row]))
matrix_percent=np.array(matrix_percent)
group_counts = ["{0:0.0f}".format(value) for value in cf_matrix.flatten()]
group_percentages = ["{0:.2%}".format(value) for value in matrix_percent.flatten()]
labels = [f"{v1}\n{v2}" for v1, v2 in zip(group_counts,group_percentages)]
labels = np.asarray(labels).reshape(len(list_name_classes),len(list_name_classes))
mat = sns.heatmap(matrix_percent, annot=labels, fmt='', cmap="magma", cbar=True,vmin=0, vmax=1,ax=ax)
labels=list_name_classes
mat.set_xticklabels(labels)
mat.set_yticklabels(labels)
mat.set(ylabel="True Label", xlabel="Predicted Label")
return(ax)