You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何增大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 using set_xticklabels and set_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:36:42