user12587364
user12587364

Reputation:

how to plot confusion matrix without color coding

Of all the answers I see on stackoverflow, such as 1, 2 and 3 are color-coded.

In my case, I wouldn´t like it to be colored, especially since my dataset is largely imbalanced, minority classes are always shown in light color. I would instead, prefer it display the number of actual/predicted in each cell.

Currently, I use:

def plot_confusion_matrix(cm, classes, title,
                          normalize=False,
                          file='confusion_matrix',
                          cmap=plt.cm.Blues):
    
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        cm_title = "Normalized confusion matrix"
    else:
        cm_title = title

    # print(cm)

    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(cm_title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = '.3f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True class')
    plt.xlabel('Predicted class')
    plt.tight_layout()
    plt.savefig(file + '.png')

Output:

enter image description here

So I want the number shown only.

Upvotes: 6

Views: 3399

Answers (2)

tdy
tdy

Reputation: 41347

Use seaborn.heatmap with a grayscale colormap and set vmin=0, vmax=0:

import seaborn as sns

sns.heatmap(cm, fmt='d', annot=True, square=True,
            cmap='gray_r', vmin=0, vmax=0,  # set all to white
            linewidths=0.5, linecolor='k',  # draw black grid lines
            cbar=False)                     # disable colorbar

# re-enable outer spines
sns.despine(left=False, right=False, top=False, bottom=False)

Complete function:

def plot_confusion_matrix(cm, classes, title,
                          normalize=False,
                          file='confusion_matrix',
                          cmap='gray_r',
                          linecolor='k'):
    
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        cm_title = 'Confusion matrix, with normalization'
    else:
        cm_title = title

    fmt = '.3f' if normalize else 'd'
    sns.heatmap(cm, fmt=fmt, annot=True, square=True,
                xticklabels=classes, yticklabels=classes,
                cmap=cmap, vmin=0, vmax=0,
                linewidths=0.5, linecolor=linecolor,
                cbar=False)
    sns.despine(left=False, right=False, top=False, bottom=False)

    plt.title(cm_title)
    plt.ylabel('True class')
    plt.xlabel('Predicted class')
    plt.tight_layout()
    plt.savefig(f'{file}.png')

Upvotes: 6

JohanC
JohanC

Reputation: 80379

You can use a ListedColormap with just one color for the colormap. Using Seaborn would automate a lot of stuff, including:

  • setting annotations at the correct spot, with either black or white depending on the cell's darkness
  • some parameters to set division lines
  • parameters to set the tick labels
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
import pandas as pd
import seaborn as sns

def plot_confusion_matrix(cm, classes, title,
                          normalize=False, file='confusion_matrix', background='aliceblue'):
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        plt.title("Normalized confusion matrix")
    else:
        plt.title(title)

    fmt = '.3f' if normalize else 'd'
    sns.heatmap(np.zeros_like(cm), annot=cm, fmt=fmt,
                xticklabels=classes, yticklabels=classes,
                cmap=ListedColormap([background]), linewidths=1, linecolor='navy', clip_on=False, cbar=False)
    plt.tick_params(axis='x', labelrotation=30)

    plt.tight_layout()
    plt.ylabel('True class')
    plt.xlabel('Predicted class')
    plt.tight_layout()
    plt.savefig(file + '.png')

cm = np.random.randint(1, 20000, (5, 5))
plot_confusion_matrix(cm, [*'abcde'], 'title')

heatmap with single color

Upvotes: 1

Related Questions