Skip to content

Commit 8c94072

Browse files
feat(matplotlib): implement confusion-matrix (#2282)
## Implementation: `confusion-matrix` - matplotlib Implements the **matplotlib** version of `confusion-matrix`. **File:** `plots/confusion-matrix/implementations/matplotlib.py` --- :robot: *[impl-generate workflow](https://github.com/MarkusNeusinger/pyplots/actions/runs/20526590092)* --------- Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
1 parent 8df91b8 commit 8c94072

2 files changed

Lines changed: 107 additions & 0 deletions

File tree

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
""" pyplots.ai
2+
confusion-matrix: Confusion Matrix Heatmap
3+
Library: matplotlib 3.10.8 | Python 3.13.11
4+
Quality: 93/100 | Created: 2025-12-26
5+
"""
6+
7+
import matplotlib.pyplot as plt
8+
import numpy as np
9+
10+
11+
# Data - Multi-class classification results (4 classes)
12+
np.random.seed(42)
13+
14+
class_names = ["Cat", "Dog", "Bird", "Fish"]
15+
n_classes = len(class_names)
16+
17+
# Create realistic confusion matrix with some misclassifications
18+
# Diagonal has highest values (correct predictions)
19+
# Off-diagonal shows realistic confusion patterns
20+
confusion_matrix = np.array(
21+
[
22+
[85, 8, 4, 3], # Cat: mostly correct, some confused with Dog
23+
[12, 78, 6, 4], # Dog: mostly correct, some confused with Cat
24+
[3, 5, 88, 4], # Bird: high accuracy
25+
[2, 3, 5, 90], # Fish: highest accuracy
26+
]
27+
)
28+
29+
# Create plot (square format for symmetric matrix)
30+
fig, ax = plt.subplots(figsize=(12, 12))
31+
32+
# Create heatmap with Blues colormap
33+
im = ax.imshow(confusion_matrix, cmap="Blues", aspect="equal")
34+
35+
# Add colorbar
36+
cbar = ax.figure.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
37+
cbar.ax.tick_params(labelsize=16)
38+
cbar.set_label("Count", fontsize=18)
39+
40+
# Set ticks and labels
41+
ax.set_xticks(np.arange(n_classes))
42+
ax.set_yticks(np.arange(n_classes))
43+
ax.set_xticklabels(class_names, fontsize=18)
44+
ax.set_yticklabels(class_names, fontsize=18)
45+
46+
# Rotate x-axis labels for better readability
47+
plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor")
48+
49+
# Annotate cells with counts and percentages
50+
for i in range(n_classes):
51+
for j in range(n_classes):
52+
count = confusion_matrix[i, j]
53+
row_total = confusion_matrix[i, :].sum()
54+
percentage = count / row_total * 100
55+
56+
# Choose text color based on background intensity
57+
text_color = "white" if count > confusion_matrix.max() * 0.5 else "black"
58+
59+
# Display count and percentage
60+
text = ax.text(
61+
j,
62+
i,
63+
f"{count}\n({percentage:.1f}%)",
64+
ha="center",
65+
va="center",
66+
color=text_color,
67+
fontsize=16,
68+
fontweight="bold",
69+
)
70+
71+
# Labels and title
72+
ax.set_xlabel("Predicted Label", fontsize=20)
73+
ax.set_ylabel("True Label", fontsize=20)
74+
ax.set_title("confusion-matrix · matplotlib · pyplots.ai", fontsize=24, pad=20)
75+
76+
# Add subtle grid lines between cells
77+
ax.set_xticks(np.arange(n_classes + 1) - 0.5, minor=True)
78+
ax.set_yticks(np.arange(n_classes + 1) - 0.5, minor=True)
79+
ax.grid(which="minor", color="white", linestyle="-", linewidth=2)
80+
ax.tick_params(which="minor", bottom=False, left=False)
81+
82+
plt.tight_layout()
83+
plt.savefig("plot.png", dpi=300, bbox_inches="tight")
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
library: matplotlib
2+
specification_id: confusion-matrix
3+
created: '2025-12-26T17:36:06Z'
4+
updated: '2025-12-26T17:39:39Z'
5+
generated_by: claude-opus-4-5-20251101
6+
workflow_run: 20526590092
7+
issue: 0
8+
python_version: 3.13.11
9+
library_version: 3.10.8
10+
preview_url: https://storage.googleapis.com/pyplots-images/plots/confusion-matrix/matplotlib/plot.png
11+
preview_thumb: https://storage.googleapis.com/pyplots-images/plots/confusion-matrix/matplotlib/plot_thumb.png
12+
preview_html: null
13+
quality_score: 93
14+
review:
15+
strengths:
16+
- Excellent text contrast with adaptive white/black text based on background intensity
17+
- Row-normalized percentages provide additional insight beyond raw counts
18+
- Realistic multi-class classification scenario with plausible confusion patterns
19+
- Clean KISS code structure with proper seed for reproducibility
20+
- Square aspect ratio perfect for symmetric confusion matrix
21+
- Professional colorbar with clear Count label
22+
weaknesses:
23+
- Does not leverage matplotlib-specific advanced features (just uses basic imshow)
24+
- Grid lines at width=2 are slightly prominent compared to subtle alpha=0.3 guidelines

0 commit comments

Comments
 (0)