如何用Python Seaborn创建含标准化特征与t检验值的组合热力图
合并Seaborn热力图为组合单图的解决方案
你需要将z-score标准化的特征热力图与t检验值、p值的热力图合并为一个相连的单图,核心是调整布局的宽度比例,让两个热力图的单元格对齐,同时统一坐标轴显示,具体修改如下:
关键调整点
- 调整
gridspec的width_ratios,匹配两部分的列数(特征列3列,t/p列2列),确保两个热力图的单元格宽度一致,视觉上紧密相连 - 隐藏第二个热力图的y轴标签和刻度,因为两行数据是对应的,避免重复显示
- 统一整体标题,去掉子图各自的标题,让图表更连贯
- 确保色条与对应热力图的配色匹配,位置合理
修改后的完整代码
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from matplotlib import gridspec # 示例DataFrame data = { 'Feature1': np.random.randn(10), 'Feature2': np.random.randn(10), 'Feature3': np.random.randn(10), 't test': np.random.randn(10), 'p value': np.random.rand(10) } df = pd.DataFrame(data) # 提取特征列并做z-score标准化 df_features_zscore = (df.iloc[:, :-2] - df.iloc[:, :-2].mean()) / df.iloc[:, :-2].std() # 提取t检验和p值列 df_stats = df[['t test', 'p value']] # 设置布局:1行4列,宽度比例对应特征列数、统计列数、两个色条宽度 fig = plt.figure(figsize=(12, 8)) gs = gridspec.GridSpec(1, 4, width_ratios=[3, 2, 0.05, 0.05]) # 绘制特征热力图 ax1 = plt.subplot(gs[0]) sns.heatmap(df_features_zscore, cmap='coolwarm', annot=True, cbar=False, ax=ax1) ax1.set_title('') # 去掉子图标题 ax1.set_ylabel('样本索引') ax1.set_xlabel('标准化特征') # 绘制统计量热力图 ax2 = plt.subplot(gs[1]) sns.heatmap(df_stats, cmap='viridis', annot=True, fmt=".4f", cbar=False, ax=ax2) ax2.set_title('') # 去掉子图标题 ax2.set_ylabel('') # 隐藏y轴标签 ax2.set_yticks([]) # 隐藏y轴刻度 ax2.set_xlabel('统计量') # 添加特征热力图的色条 cbar_ax1 = plt.subplot(gs[2]) cbar1 = plt.colorbar(ax1.collections[0], cax=cbar_ax1, orientation='vertical') cbar1.set_label('Z-score') # 添加统计量热力图的色条 cbar_ax2 = plt.subplot(gs[3]) cbar2 = plt.colorbar(ax2.collections[0], cax=cbar_ax2, orientation='vertical') cbar2.set_label('统计量值') # 添加整体标题 fig.suptitle('特征标准化值与统计量组合热力图', y=1.02, fontsize=14) plt.tight_layout() plt.show()
效果说明
修改后两个热力图会紧密连接,单元格宽度一致,视觉上是一个完整的组合图;y轴只在左侧显示一次,避免冗余;两个色条分别对应各自区域的配色,清晰区分不同数据的含义。
内容的提问来源于stack exchange,提问作者Umar
相关产品推荐
相关产品推荐

