Plot a Confusion Matrix from caret's confusionMatrix Object
Source:R/plot_confusion_matrix.R
plot_confusion_matrix.RdCreates an elegant heatmap visualization of a confusion matrix using ggplot2. The plot displays predicted vs actual class counts with color-coded cells and numeric labels for easy interpretation.
Usage
plot_confusion_matrix(
cm,
title = "Confusion Matrix",
xlab = "Reference",
ylab = "Prediction",
low_color = "white",
high_color = "steelblue",
text_color = "black",
text_size = 5
)Arguments
- cm
An object of class "confusionMatrix" created by
confusionMatrixfrom the caret package.- title
A character string for the plot title (default: "Confusion Matrix").
- xlab
Label for the x-axis representing true/reference classes (default: "Reference").
- ylab
Label for the y-axis representing predicted classes (default: "Prediction").
- low_color
Colour gradient start for cells with low counts (default: "white").
- high_color
Colour gradient end for cells with high counts (default: "steelblue").
- text_color
Colour of the numeric count labels inside cells (default: "black").
- text_size
Size of the cell count labels in points (default: 5).
Note
The factor levels are automatically set to match the original order from the confusion matrix table, ensuring consistent axis ordering.
See also
confusionMatrix for creating confusion matrices
Examples
if (FALSE) { # \dontrun{
# Example 1: Basic usage
library(caret)
# Create sample predictions and references
set.seed(123)
actual <- factor(sample(c("A", "B", "C"), 100, replace = TRUE))
predicted <- factor(sample(c("A", "B", "C"), 100, replace = TRUE))
# Generate confusion matrix
cm <- confusionMatrix(predicted, actual)
# Plot with default settings
plot_confusion_matrix(cm)
# Example 2: Customized appearance
plot_confusion_matrix(
cm,
title = "Model Performance: Predicted vs Actual",
low_color = "#f7fbff",
high_color = "#08306b",
text_color = "white",
text_size = 4
)
} # }