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

Seaborn热力图仅显示第一行注释,是否为Bug?

Seaborn热图仅显示第一行注释的问题排查

你的代码里热图只显示第一行注释,不是Seaborn或Matplotlib的Bug,核心原因是0值单元格的注释文本颜色和背景色对比度为0,导致肉眼无法识别:

Seaborn默认的热图配色中,0值对应的背景色接近白色,而注释文本默认颜色也是白色,这些0值的注释其实已经渲染,只是被背景完全覆盖了。

解决方法

有两种简单的修复方式:

  • 自定义注释文本颜色,确保和所有背景色有足够对比度:
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

matrix = np.array([[0.1234, 1.4567, 0.7890, 0.1234],
                   [0.9876, 0, 0.5432, 0.6789],
                   [0.1111, 0.2222, 0, 0.3333],
                   [0.4444, 0.5555, 0.6666, 0]])
sns.heatmap(matrix, annot=True, annot_kws={"color": "black"})
plt.show()
  • 更换热图的颜色映射,避免0值对应浅色背景:
sns.heatmap(matrix, annot=True, cmap='viridis')
plt.show()

额外优化

可以通过fmt参数控制注释的数值格式,比如保留两位小数,让显示更清爽:

sns.heatmap(matrix, annot=True, annot_kws={"color": "black"}, fmt=".2f")

内容的提问来源于stack exchange,提问作者Mantas Kandratavičius

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 11:30:15