如何将混淆矩阵的X轴预测标签(0、1)移至顶部?
I'm using the following Python code to plot a confusion matrix for a Random Forest model:
from sklearn.metrics import accuracy_score plt.figure(figsize=(6,4)) sns.heatmap(cm_rf, annot=True, fmt="d") plt.title('Random Forest Tree \nAccuracy:{0:.3%}\n'.format(accuracy_score(test_y, predict_rf_y))) plt.ylabel('True label') plt.xlabel('Predicted label') plt.show()
Is there a way to move the X-axis labels (the 0 and 1 under "Predicted label") to the top of the confusion matrix? I'd appreciate any help with this!
Absolutely! You can adjust the position of the x-axis ticks and labels using matplotlib's built-in functions alongside seaborn's heatmap settings. Here are two straightforward, reliable approaches:
Approach 1: Use tick_params and set_xlabel with position control
After creating the heatmap, you can explicitly shift the x-axis ticks to the top and reposition the main x-label accordingly:
from sklearn.metrics import accuracy_score import matplotlib.pyplot as plt import seaborn as sns plt.figure(figsize=(6,4)) # Assign the heatmap to an axis object for easy manipulation ax = sns.heatmap(cm_rf, annot=True, fmt="d") # Move x-axis ticks and their labels to the top, hide bottom ones ax.tick_params(axis='x', top=True, bottom=False, labeltop=True, labelbottom=False) # Set the x-label to sit at the top with proper padding ax.set_xlabel('Predicted label', labelpad=12, loc='top') ax.set_ylabel('True label') ax.set_title('Random Forest Tree \nAccuracy:{0:.3%}\n'.format(accuracy_score(test_y, predict_rf_y))) plt.show()
Approach 2: Use xaxis.set_label_position
This method directly tells matplotlib to place the x-axis label at the top, paired with tick adjustments:
from sklearn.metrics import accuracy_score import matplotlib.pyplot as plt import seaborn as sns plt.figure(figsize=(6,4)) ax = sns.heatmap(cm_rf, annot=True, fmt="d") # Set x-axis label position to top ax.xaxis.set_label_position('top') # Toggle tick visibility to show only top ticks/labels ax.tick_params(axis='x', top=True, bottom=False, labeltop=True, labelbottom=False) ax.set_xlabel('Predicted label') ax.set_ylabel('True label') ax.set_title('Random Forest Tree \nAccuracy:{0:.3%}\n'.format(accuracy_score(test_y, predict_rf_y))) plt.show()
Both methods will move both the "Predicted label" text and the 0/1 tick labels to the top of your confusion matrix. The core idea is controlling tick visibility with tick_params and adjusting the label's anchor point to sit above the plot instead of below.
内容的提问来源于stack exchange,提问作者user7648646

