i have a problem. I've created a confusion matrix which looks like this:
the following code is this one:
cm = np.array([[2547,288],[ 255,216]])
fig, ax = plt.subplots(figsize=(12, 8))
ax = sns.heatmap(cm, annot=True, cmap='BuPu', fmt='g')
ax.set_title('Seaborn Confusion Matrix with labels\n\n');
ax.set_xlabel('\nPredicted Values')
ax.set_ylabel('Actual Values ');
## Ticket labels - List must be in alphabetical order
ax.xaxis.set_ticklabels(['True','False'])
ax.yaxis.set_ticklabels(['True','False'])
## Display the visualization of the Confusion Matrix.
plt.show()
this is most likely fine but i want it to look a little bit different like this:
as you can see, the colors which should be correct are green and the other ones red and aswell i want to show the labels (true positive, true negative, ...). And a label should be for the actual and predicted and for the negative and positive values. So 1:1 as you can see in the photo below.
is there a way i can add the labels and correct the colors in seaborn? Ty very much for your help !
CodePudding user response:
You can create a heatmap with a unity matrix as data, and the numbers you want as annotation. Use a colormap created as a palette from just two colors (first the color for 0, then the color for 1). Seaborn will take care to use the appropriate text color.
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
sns.set(style='white')
cm = np.array([[2547, 288], [255, 216]])
fig, ax = plt.subplots(figsize=(12, 8))
sns.heatmap(np.eye(2), annot=cm, fmt='g', annot_kws={'size': 50},
cmap=sns.color_palette(['tomato', 'palegreen'], as_cmap=True), cbar=False,
yticklabels=['True', 'False'], xticklabels=['True', 'False'], ax=ax)
ax.xaxis.tick_top()
ax.xaxis.set_label_position('top')
ax.tick_params(labelsize=20, length=0)
ax.set_title('Seaborn Confusion Matrix with labels', size=24, pad=20)
ax.set_xlabel('Predicted Values', size=20)
ax.set_ylabel('Actual Values', size=20)
additional_texts = ['(True Positive)', '(False Negative)', '(False Positive)', '(True Negative)']
for text_elt, additional_text in zip(ax.texts, additional_texts):
ax.text(*text_elt.get_position(), '\n' additional_text, color=text_elt.get_color(),
ha='center', va='top', size=24)
plt.tight_layout()
plt.show()