组合绘制Clustermap与Heatmap时双颜色条配置问题求助
组学数据对比可视化问题解决方案
1. 统一颜色条配置
- 左侧Clustermap:通过
cbar_kws参数开启颜色条刻度,同时用shrink和aspect固定颜色条尺寸,确保显示数据范围刻度 - 右侧Heatmap:复用Clustermap的颜色条尺寸参数,指定
cbar_kws={'location': 'right'}将颜色条放在右侧,同步开启刻度显示;若需更精准位置控制,可手动创建颜色条轴并通过cbar_ax传入
2. Clustermap标题与x轴标签调整
- 自定义标题:利用Clustermap返回对象的
fig属性,调用fig.suptitle()设置全局标题,配合y参数调整位置避免与图重叠 - 移除x轴"group"标签:通过Clustermap对象的
ax_heatmap属性,执行set_xlabel('')清空标签
修改后的可复现代码
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd import numpy as np # 模拟两组组学数据集 np.random.seed(42) genes = [f'Gene_{i}' for i in range(50)] groups = ['Group_A', 'Group_B', 'Group_C'] data1 = pd.DataFrame(np.random.randn(50, 3), index=genes, columns=groups) data2 = pd.DataFrame(np.random.randn(50, 3), index=genes, columns=groups) # 绘制Clustermap并提取基因顺序 g = sns.clustermap(data1, cmap='coolwarm', # 配置颜色条:显示刻度、固定尺寸 cbar_kws={'ticks': np.arange(-2, 3, 1), 'shrink': 0.8, 'aspect': 20, 'label': 'Expression Level'}) # 获取聚类后的基因排序 ordered_genes = g.dendrogram_row.reordered_ind data2_ordered = data2.iloc[ordered_genes] # 调整Clustermap标题与x轴标签 g.fig.suptitle('Clustermap of Dataset 1', y=1.02, fontsize=12) g.ax_heatmap.set_xlabel('') # 移除默认x轴标签 # 绘制匹配基因顺序的Heatmap,统一颜色条样式 plt.figure(figsize=(4, 8)) sns.heatmap(data2_ordered, cmap='coolwarm', # 对齐左侧颜色条尺寸,放在右侧并显示刻度 cbar_kws={'location': 'right', 'ticks': np.arange(-2, 3, 1), 'shrink': 0.8, 'aspect': 20, 'label': 'Expression Level'}) plt.title('Heatmap of Dataset 2 (Matched Order)', y=1.02) plt.tight_layout() plt.show()
关键细节
- 颜色条的
shrink(缩放比例)和aspect(宽高比)参数需两组保持一致,实现视觉统一 - Clustermap的
ax_heatmap是热图区域的轴对象,直接操作可修改x轴标签等属性 - 若需更精细的布局对齐,可手动拆分画布布局,预留颜色条的专属空间
内容的提问来源于stack exchange,提问作者WilkeM
相关产品推荐
相关产品推荐

