Yoann
Yoann

Reputation: 1

Clickable matrix python figure to highlight given row and column

Hello :) Does anybody know how to make a matplotlib matrix figure clickable?

For instance, if I click a cell of the matrix, it should highlight the row and the column of this cell (see the before and after pictures below, where the background of the corresponding row and column turn green after clicking the middle cell in this example). The figure should be clickable after exporting it (so we can click it when imported in a pdf for instance), but not necessarily when displayed in jupyter notebook.

Here is the code I am using to plot the confusion matrix :

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)

Before
enter image description here

After
enter image description here

Upvotes: 0

Views: 253

Answers (0)

Related Questions