Search code examples
pythonscikit-learnconfusion-matrix

scikit-learn's ConfusionMatrixDisplay() with figsize()


Using figsize() in the following code creates two plots of the confusion matrix, one with the desired size but wrong labels ("Figure 1") and another with the default/wrong size but correct labels ("Figure 2") (image attached below). Second plot is what I want, but with the specified size 8x6in. How do I do this? Thanks!

import matplotlib.pyplot as plt
from sklearn import datasets, svm
from sklearn.metrics import ConfusionMatrixDisplay

# import data
iris = datasets.load_iris()
X, y = iris.data, iris.target

# Run classifier
classifier = svm.SVC(kernel="linear")
y_pred = classifier.fit(X, y).predict(X)

# plot confusion matrix
fig, ax = plt.subplots(figsize=(8, 6))
cmp = ConfusionMatrixDisplay.from_predictions(y, y_pred, normalize="true", values_format=".0%")
cmp.plot(ax=ax)
plt.show()

enter image description here


Solution

  • It is not figsize() which is generating two plots rather you are calling ConfusionMatrixDisplay.from_predictions() twice which is generating the two plots. The ConfusionMatrixDisplay itself returns a visualization plot so you don't need to call cmp.plot() again.

    Replace the following code:

    # plot confusion matrix
    fig, ax = plt.subplots(figsize=(8, 6))
    cmp = ConfusionMatrixDisplay.from_predictions(y, y_pred, normalize="true", values_format=".0%")
    cmp.plot(ax=ax)
    plt.show()
    

    with this:

    # plot confusion matrix
    fig, ax = plt.subplots(figsize=(8, 6))
    cmp = ConfusionMatrixDisplay.from_predictions(y, y_pred, normalize="true", values_format=".0%", ax = ax)