如何用Pingouin的rcorr结果绘制带显著性标记的热力图?
解决Pingouin rcorr()结果适配Seaborn热力图的方案
1. 精准提取相关系数数值
Pingouin的rcorr()返回的是带显著性标记的字符串结果(比如"0.87***"或"-"),直接用replace处理容易覆盖不全,用正则表达式提取纯数值更可靠:
import pingouin as pg import seaborn as sns import matplotlib.pyplot as plt import re import numpy as np # 示例数据 df = pg.read_dataset('iris') corr_results = df.rcorr(method='pearson', upper='significance') # 自定义提取函数:处理"-"和带标记的数值 def get_corr_num(s): if s == '-': return 1.0 num_match = re.search(r'-?\d+\.?\d*', str(s)) return float(num_match.group()) if num_match else np.nan # 生成纯数值相关系数矩阵 corr_matrix = corr_results.applymap(get_corr_num)
2. 上三角保留显著性标记的绘图方案
要实现下三角/对角线显示系数、上三角显示显著性的效果,可自定义标注矩阵:
# 构建标注矩阵 annot_matrix = corr_results.copy() # 处理下三角:格式化显示系数 for i in range(annot_matrix.shape[0]): for j in range(i+1): val = get_corr_num(annot_matrix.iloc[i,j]) annot_matrix.iloc[i,j] = f'{val:.2f}' # 处理上三角:提取显著性标记 for i in range(annot_matrix.shape[0]): for j in range(i+1, annot_matrix.shape[1]): sig_match = re.search(r'\*+', annot_matrix.iloc[i,j]) annot_matrix.iloc[i,j] = sig_match.group() if sig_match else '' # 绘制热力图 plt.figure(figsize=(10,8)) sns.heatmap(corr_matrix, annot=annot_matrix.values, fmt='', cmap='coolwarm', square=True, linewidths=0.5, cbar=True) plt.title('Correlation Matrix with Significance Annotations') plt.show()
3. 更高效的替代思路
直接用rcorr()的return_results=True参数,分别获取纯数值的相关系数矩阵和p值矩阵,手动生成带显著性的标注:
# 分离系数和p值矩阵 corr, pval = df.rcorr(method='pearson', return_results=True) # 根据p值生成带标记的标注 annot = np.where(pval < 0.001, corr.round(2).astype(str) + '***', np.where(pval < 0.01, corr.round(2).astype(str) + '**', np.where(pval < 0.05, corr.round(2).astype(str) + '*', corr.round(2).astype(str)))) # 补全对角线数值 np.fill_diagonal(corr, 1.0) # 绘图 sns.heatmap(corr, annot=annot, fmt='', cmap='coolwarm') plt.show()
内容的提问来源于stack exchange,提问作者molcode
相关产品推荐
相关产品推荐

