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

如何调整Seaborn热力图中星号至数值方格内部右上角

问题:调整Seaborn热力图显著性星号至方格右上角

希望将Seaborn热力图中显著性星号的位置调整到数值所在方格的内部右上角(靠近角落处),而非在数值上方,以此提升可视化的可读性,请问该需求能否实现?

解决方案:可以实现

核心思路是放弃使用seaborn.heatmap自带的annot参数自动生成注释,改为手动绘制数值和星号,分别控制两者的位置。以下是修改后的完整代码:

from string import ascii_letters
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.stats import pearsonr

sns.set_theme(style="white")
rs = np.random.RandomState(33)
df = pd.DataFrame(data=rs.normal(size=(100, 26)),
                 columns=list(ascii_letters[26:]))

# 计算相关系数和p值,整理标注内容
correlations = df.corr()
annotations = pd.DataFrame(index=df.columns, columns=df.columns)
sig_markers = pd.DataFrame(False, index=df.columns, columns=df.columns)  # 标记是否需要加星号

for col1 in df.columns:
    for col2 in df.columns:
        if col1 != col2:
            corr, p = pearsonr(df[col1], df[col2])
            annotations.loc[col1, col2] = f"{corr:.2f}"
            if p < 0.05:
                sig_markers.loc[col1, col2] = True
        else:
            annotations.loc[col1, col2] = f"{1:.2f}"

# 自定义色卡
cmap = sns.diverging_palette(250, 10, as_cmap=True)
# 上三角掩码
mask = np.triu(np.ones_like(correlations, dtype=bool))

plt.figure(figsize=(20, 15))
# 先绘制不带注释的热力图
ax = sns.heatmap(correlations, mask=mask, cmap=cmap, vmax=1, center=0, vmin=-1,
            square=True, linewidths=.5, cbar_kws={"shrink": .5}, annot=False)

# 获取坐标轴刻度的索引位置
x_ticks = ax.get_xticks()
y_ticks = ax.get_yticks()

# 遍历每个单元格,手动添加数值和星号
for i, col1 in enumerate(df.columns):
    for j, col2 in enumerate(df.columns):
        if mask[i, j]:
            continue  # 跳过被掩码的单元格
        # 获取当前单元格的中心坐标
        x = x_ticks[j]
        y = y_ticks[i]
        # 绘制数值(居中)
        ax.text(x, y, annotations.loc[col1, col2], 
                ha='center', va='center', fontsize=10)
        # 如果需要加星号,在右上角绘制
        if sig_markers.loc[col1, col2]:
            ax.text(x + 0.35, y + 0.35, "*", 
                    ha='center', va='center', fontsize=12, color='red')

plt.title('Correlation Matrix')
plt.show()

关键说明:

  • 先绘制不带注释的热力图(annot=False),避免自动生成的注释干扰
  • 通过坐标轴刻度获取每个单元格的中心坐标,分别绘制居中的数值
  • 对需要标注显著性的单元格,通过坐标偏移(x+0.35、y+0.35)将星号定位到方格右上角,偏移量可根据实际需求微调
  • 用单独的矩阵标记需要加星号的单元格,清晰分离数值和星号的绘制逻辑

内容的提问来源于stack exchange,提问作者Nemo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 02:27:47