HOWTO · Python
How to Plot Confusion Matrix in Python
Learn to plot and label a confusion matrix in Python with Matplotlib, Seaborn, or Pretty Confusion Matrix.
On this page
To plot a confusion matrix in Python, count each actual and predicted class pair, then display those counts with Matplotlib or Seaborn. This article also introduces the package-based Pretty Confusion Matrix option. Rows represent actual classes and columns represent predicted classes.
Use Matplotlib to Plot Confusion Matrix in Python
A confusion matrix stores the count for each actual and predicted class pair. Define the class order once so the matrix rows and columns match the axis labels. In this example, y_true contains the observed class for each item and y_pred contains the corresponding model prediction. The first row and column represent bat; the second row and column represent ball. The following runnable example builds the count matrix using only Python’s standard library.
Run this example:
classes = ["bat", "ball"]
y_true = ["bat", "ball", "ball", "bat", "bat", "bat"]
y_pred = ["bat", "bat", "ball", "ball", "bat", "bat"]
matrix = [
[sum(actual == row and predicted == column
for actual, predicted in zip(y_true, y_pred))
for column in classes]
for row in classes
]
print(matrix)
[[3, 1], [1, 1]]
The complete Matplotlib program below saves the finished plot to confusion-matrix-matplotlib.png, so it runs the same with or without a display; in an interactive session, you can replace the savefig line with plt.show().
import matplotlib.pyplot as plt
classes = ["bat", "ball"]
y_true = ["bat", "ball", "ball", "bat", "bat", "bat"]
y_pred = ["bat", "bat", "ball", "ball", "bat", "bat"]
matrix = [
[sum(actual == row and predicted == column
for actual, predicted in zip(y_true, y_pred))
for column in classes]
for row in classes
]
fig, ax = plt.subplots(figsize=(5, 4))
image = ax.imshow(matrix, cmap="Blues", origin="upper")
fig.colorbar(image, ax=ax, label="Count")
for row in range(len(classes)):
for column in range(len(classes)):
value = matrix[row][column]
ax.text(column, row, str(value), ha="center", va="center",
color="white" if value > 1.5 else "black")
ax.set_xticks(range(len(classes)))
ax.set_yticks(range(len(classes)))
ax.set_xticklabels(classes)
ax.set_yticklabels(classes)
ax.set_xlabel("Predicted class")
ax.set_ylabel("Actual class")
ax.set_title("Confusion Matrix")
fig.tight_layout()
fig.savefig("confusion-matrix-matplotlib.png", bbox_inches="tight")
The matrix calculation gives [[3, 1], [1, 1]]: three actual bats were predicted as bats, one actual bat as a ball, one actual ball as a bat, and one actual ball as a ball. Diagonal cells count correct predictions; off-diagonal cells count misclassifications. These are counts, not percentages.
Rows in the plot are actual labels, and columns are predicted labels. The annotation loop reads matrix[row][column] but passes (column, row) to ax.text, because x is horizontal and y is vertical. For an asymmetric matrix such as [[3, 2], [1, 4]], this places 2 at x=1, y=0 and 1 at x=0, y=1; swapping those coordinates would mislabel the cells. origin="upper" keeps the first actual class at the top.
When adapting the program, supply equally long label lists, keep corresponding observations in the same positions, and include every observed class in classes. Otherwise, zip truncates unmatched items, or the comprehension omits classes you did not declare.
Use Seaborn to Plot Confusion Matrix in Python
Seaborn’s heatmap handles cell annotations for you. This independent program defines its own data and matrix, so it does not depend on running the preceding section. It requires Seaborn and Matplotlib, and it saves its plot to confusion-matrix-seaborn.png.
import matplotlib.pyplot as plt
import seaborn as sns
classes = ["bat", "ball"]
y_true = ["bat", "ball", "ball", "bat", "bat", "bat"]
y_pred = ["bat", "bat", "ball", "ball", "bat", "bat"]
matrix = [
[sum(actual == row and predicted == column
for actual, predicted in zip(y_true, y_pred))
for column in classes]
for row in classes
]
fig, ax = plt.subplots(figsize=(5, 4))
sns.heatmap(matrix, annot=True, fmt="d", cmap="Blues", square=True,
xticklabels=classes, yticklabels=classes,
cbar_kws={"label": "Count"}, ax=ax)
ax.set_xlabel("Predicted class")
ax.set_ylabel("Actual class")
ax.set_title("Confusion Matrix")
ax.tick_params(axis="y", labelrotation=0)
fig.tight_layout()
fig.savefig("confusion-matrix-seaborn.png", bbox_inches="tight")
Here, annot=True writes the values into the cells and fmt="d" formats them as integers. The count calculation again gives [[3, 1], [1, 1]]. Both tick-label lists follow the declared order, bat then ball, rather than unrelated Boolean labels. Actual classes run down the vertical axis; predicted classes run across the horizontal axis. Replace the paired observations and class list together when using your own data.
Use Pretty Confusion Matrix to Plot Confusion Matrix in Python
Pretty Confusion Matrix provides the pp_matrix_from_data entry point for plotting from paired actual and predicted labels. The package’s PyPI project page provides its API example, installation guidance, and dependency metadata. The distribution name is pretty-confusion-matrix, while the Python import uses underscores: pretty_confusion_matrix.
The following complete example saves the package’s plot to confusion-matrix-pretty.png. It was executed as written against the current releases of the package and its dependencies; consult the project’s dependency requirements when setting up your own environment.
import matplotlib.pyplot as plt
from pretty_confusion_matrix import pp_matrix_from_data
classes = ["bat", "ball"]
y_true = ["bat", "ball", "ball", "bat", "bat", "bat"]
y_pred = ["bat", "bat", "ball", "ball", "bat", "bat"]
# Numeric IDs make the package's sorted class order match the display names.
class_ids = {label: index for index, label in enumerate(classes)}
true_values = [class_ids[label] for label in y_true]
predicted_values = [class_ids[label] for label in y_pred]
pp_matrix_from_data(true_values, predicted_values,
columns=classes, pred_val_axis="col")
plt.savefig("confusion-matrix-pretty.png", bbox_inches="tight")
true_values contains actual class IDs and predicted_values contains the corresponding predictions. Encoding bat as 0 and ball as 1 aligns their sorted order with columns=classes; the columns argument supplies display names rather than reordering the observations. pred_val_axis="col" selects predicted classes on columns, leaving actual classes on rows. The underlying class counts are [[3, 1], [1, 1]]; the package’s presentation can also include summary totals, so its layout differs from the two plain heatmaps above. No additional metric result is claimed here.
The plot this program produces is: