ConfusionMatrixDisplay (Scikit-Learn) plot labels out of range

Total
4
Shares

The following code plots a confusion matrix:

from sklearn.metrics import ConfusionMatrixDisplay

confusion_matrix = confusion_matrix(y_true, y_pred)
target_names = ["aaaaa", "bbbbbb", "ccccccc", "dddddddd", "eeeeeeeeee", "ffffffff", "ggggggggg"]
disp = ConfusionMatrixDisplay(confusion_matrix=confusion_matrix, display_labels=target_names)
disp.plot(cmap=plt.cm.Blues, xticks_rotation=45)
plt.savefig("conf.png")

Confusion Matrix

There are two problems with this plot.

  1. The y-axis label is cut off (True Label). The x label is cut off too.
  2. The names are to long for the x-axis.

To solve the first problem I tried to use poof(bbox_inches='tight') which is unfortunately not available for sklearn.
In the second case I tried the following solution for 2. which lead to a completely distorted plot.

All in all I’m struggeling with both problems.


Solution

I think the easiest way would be to switch into tight_layout and add pad_inches= something.

from sklearn.metrics import confusion_matrix
from sklearn.metrics import ConfusionMatrixDisplay
import matplotlib.pyplot as plt
from numpy.random import default_rng

rand = default_rng()
y_true = rand.integers(low=0, high=7, size=500)
y_pred = rand.integers(low=0, high=7, size=500)


confusion_matrix = confusion_matrix(y_true, y_pred)
target_names = ["aaaaa", "bbbbbb", "ccccccc", "dddddddd", "eeeeeeeeee", "ffffffff", "ggggggggg"]
disp = ConfusionMatrixDisplay(confusion_matrix=confusion_matrix, display_labels=target_names)
disp.plot(cmap=plt.cm.Blues, xticks_rotation=45)

plt.tight_layout()
plt.savefig("conf.png", pad_inches=5)

Result:

Confusion matrix where all text in the axes is visible.

Leave a Reply

Your email address will not be published. Required fields are marked *