Adjust size of ConfusionMatrixDisplay (ScikitLearn)

Question:

How to set the size of the figure ploted by ScikitLearn’s Confusion Matrix?

import numpy as np
from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix
cm = confusion_matrix(np.arange(25), np.arange(25))
cmp = ConfusionMatrixDisplay(cm, display_labels=np.arange(25))
cmp.plot()

The code above shows this figure, which is too tight:

enter image description here

Asked By: Raphael

||

Answers:

You can send a matplotlib.axes object to the .plot method of sklearn.metrics.ConfusionMatrixDisplay. Set the size of the figure in matplotlib.pyplot.subplots first.

import numpy as np
from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix
import matplotlib.pyplot as plt

cm = confusion_matrix(np.arange(25), np.arange(25))
cmp = ConfusionMatrixDisplay(cm, display_labels=np.arange(25))
fig, ax = plt.subplots(figsize=(10,10))
cmp.plot(ax=ax)

enter image description here

Answered By: Raphael

I was looking for how to adjust the colorbar as someone pointed out in the commentaries in the answer offered by @Raphael and now want to add how to made this.

I used the properties of ConfusionMatrixDisplay and guided by this answer modified the code to:

import numpy as np
from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix
import matplotlib.pyplot as plt

cm = confusion_matrix(np.arange(25), np.arange(25))
cmp = ConfusionMatrixDisplay(cm, display_labels=np.arange(25))
fig, ax = plt.subplots(figsize=(10,10))

# Deactivate default colorbar
cmp.plot(ax=ax, colorbar=False)

# Adding custom colorbar
cax = fig.add_axes([ax.get_position().x1+0.01,ax.get_position().y0,0.02,ax.get_position().height])
plt.colorbar(cmp.im_,  cax=cax)

enter image description here

Answered By: StandardIO