2

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.

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Jürgen K.
  • 3,427
  • 9
  • 30
  • 66

1 Answers1

6

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.

Alexander L. Hayes
  • 3,892
  • 4
  • 13
  • 34