如何增大ConfusionMatrix文本尺寸并设置所有文本为粗体?
Absolutely, there's a straightforward way to adjust those text properties using matplotlib's text object methods. Here's how you can modify your code to achieve both goals:
import numpy as np from sklearn.metrics import ConfusionMatrixDisplay import matplotlib.pyplot as plt array = np.array([[1003, 32], [30, 51]]) labels = np.array(["Label 1", "Label 2"]) disp = ConfusionMatrixDisplay(confusion_matrix=array, display_labels=labels) disp = disp.plot(include_values=True, cmap="Reds", ax=None, xticks_rotation="horizontal") # Customize matrix values: increase size and make bold for text_element in disp.text_.flatten(): text_element.set_fontsize(14) # Adjust this value to your preferred size text_element.set_fontweight("bold") # Customize axis labels (display_labels): increase size and make bold disp.ax.set_xticklabels( disp.ax.get_xticklabels(), fontsize=14, fontweight="bold" ) disp.ax.set_yticklabels( disp.ax.get_yticklabels(), fontsize=14, fontweight="bold" ) plt.show()
Breakdown of the changes:
- Matrix values: The
disp.text_attribute holds a 2D array of matplotlib Text objects for each number inside the confusion matrix cells. We flatten this array and loop through each element to set the font size and weight. - Axis labels: We access the existing tick labels from the axes object (
disp.ax), then reapply them with the desired font size and bold formatting usingset_xticklabelsandset_yticklabels.
You can tweak the fontsize value (14 in this example) to match your needs—larger numbers will make the text bigger. This approach keeps things concise and directly modifies the elements you care about without needing complex workarounds.
内容的提问来源于stack exchange,提问作者hafnerl
相关产品推荐
相关产品推荐

