Home > OS >  How label to the data (not the axes) of the plot of a confusion matrix that displays True Positive,
How label to the data (not the axes) of the plot of a confusion matrix that displays True Positive,

Time:02-11

I am trying to label the plot of my confusion matrix. The first image below is what my plot currently shows. The subsequent image is what I want to emulate. Here are the features I want to add in order of importance.

  1. Need to have the data labeled like TP = 374 etc.
  2. Can I set background color of xlabels and ylabels?
  3. Can I specify the face colors since there are only 4 quadrants?

Current Plot The plot I am trying to create

CodePudding user response:

You can use seaborn's heatmap with explicit annotations. The colors are defined by the data values in combination with the colormap.

import matplotlib.pyplot as plt
import seaborn as sns

cm = [[327, 237], [289, 200]]
sns.set(font_scale=3)
plt.figure(figsize=(7, 7))
ax = sns.heatmap(data=[[1, 0], [0, 1]], cmap=sns.color_palette(['tomato', 'lightgreen'], as_cmap=True),
                 annot=[[f"TP={cm[0][0]:.0f}", f"FP={cm[0][1]:.0f}"], [f"FN={cm[1][0]:.0f}", f"TN={cm[1][1]:.0f}"]],
                 fmt='', annot_kws={'fontsize': 30}, cbar=False, square=True)

ax.set_xlabel('Actual Values')
ax.set_ylabel('Predicted')
ax.tick_params(length=0, labeltop=True, labelbottom=False)
ax.xaxis.set_label_position('top')
ax.set_xticklabels(['Positive', 'Negative'])
ax.set_yticklabels(['Positive', 'Negative'], rotation=90, va='center')
ax.add_patch(plt.Rectangle((0, 1), 1, 0.1, color='yellow', clip_on=False, zorder=0, transform=ax.transAxes))
ax.add_patch(plt.Rectangle((0, 0), -0.1, 1, color='yellow', clip_on=False, zorder=0, transform=ax.transAxes))
plt.tight_layout()
plt.show()

sns.heatmap for confusion matrix

  • Related