为Pyplot混淆矩阵热力图添加非传统侧边数值标注
Absolutely! This is totally achievable with Python's matplotlib and seaborn libraries—even if you're new to plotting, it’s manageable with a bit of step-by-step guidance. Here’s how you can add those custom error values to your confusion matrix heatmap:
Step 1: Set up your base heatmap
First, let’s start with a basic confusion matrix heatmap (replace the example matrix with your actual data):
import matplotlib.pyplot as plt import seaborn as sns # Replace this with your real confusion matrix data confusion_matrix = [ [90, 0, 13], [6, 85, 0], [9, 0, 88] ] # Create the core heatmap plt.figure(figsize=(8, 6)) ax = sns.heatmap(confusion_matrix, annot=True, fmt='d', cmap='Blues', cbar=True) plt.title("Confusion Matrix Heatmap")
Step 2: Add omission errors (13, 0, 0) above the top-edge squares
We’ll use ax.text() to place these values right above each top cell, between the title and the heatmap:
# Coordinates for the center of each top cell (x-axis) top_x_coords = [0.5, 1.5, 2.5] # Position above the top edge of the heatmap top_y_coord = ax.get_ylim()[1] + 0.1 # Your omission error values omission_errors = [13, 0, 0] # Loop to place each value for x, val in zip(top_x_coords, omission_errors): ax.text(x, top_y_coord, str(val), ha='center', va='bottom', fontweight='bold')
Step 3: Add commission errors (0, 6, 9) to the right of the right-edge squares
Similarly, we’ll place these values between the heatmap and the color legend:
# Coordinates for the center of each right-edge cell (y-axis; note matplotlib reverses y for heatmaps) right_y_coords = [2.5, 1.5, 0.5] # Position to the right of the heatmap's edge right_x_coord = ax.get_xlim()[1] + 0.1 # Your commission error values commission_errors = [0, 6, 9] # Loop to place each value for y, val in zip(right_y_coords, commission_errors): ax.text(right_x_coord, y, str(val), ha='left', va='center', fontweight='bold')
Step 4: Adjust layout and display the plot
Finally, tweak the plot limits to make space for the new text and clean up the layout:
# Expand the plot area to fit the extra text ax.set_xlim(ax.get_xlim()[0], ax.get_xlim()[1] + 0.5) ax.set_ylim(ax.get_ylim()[0], ax.get_ylim()[1] + 0.5) plt.tight_layout() plt.show()
Quick notes for customization:
- You can adjust the offset values (like
+0.1or+0.5) to move the text closer or farther from the heatmap. - If your confusion matrix has more/fewer classes, just update the
top_x_coordsandright_y_coordslists to match the number of classes (e.g., for a 4x4 matrix, use[0.5, 1.5, 2.5, 3.5]). - Change
fontweight='bold'to other styles (likefontsize=12) if you want to tweak the text appearance.
内容的提问来源于stack exchange,提问作者SonicProtein
相关产品推荐
相关产品推荐

