如何使用 matplotlib 与归一化数据和原始 t 检验值在 Python 中创建组合热图?

问题描述 投票:0回答:1

我有一个包含多个特征及其相关 t 检验结果和 p 值的 DataFrame。我的目标是使用 Seaborn 在 Python 中生成组合热图。在此热图中,一个部分应使用 z 分数显示具有标准化数据的特征(以确保高值和低值的可见性),而另一部分应显示原始 t 检验值和 p 值。

我打算为每个部分创建一个具有不同配色方案的热图,以清楚地区分它们。然而,我尝试绘制两个单独的热图并将它们组合起来,结果得到了单独的图,而不是统一的热图。

有人可以指导我如何创建两个部分都附加的单个组合热图吗?

这是我迄今为止尝试过的代码: 将 pandas 导入为 pd 将 numpy 导入为 np 将seaborn导入为sns 将 matplotlib.pyplot 导入为 plt 从 matplotlib 导入 gridspec

# Example 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)

# Drop the last two columns
df_heatmap = df.iloc[:, :-2]

# Calculate z-scores for the DataFrame
df_heatmap_zscore = (df_heatmap - df_heatmap.mean()) / df_heatmap.std()

# Set up the layout
fig = plt.figure(figsize=(12, 8))
gs = gridspec.GridSpec(1, 4, width_ratios=[1, 1, 0.05, 0.05])  # 4 columns: 2 for heatmaps, 2 for colorbars

# Heatmap for the DataFrame excluding t-test and p-value columns
ax1 = plt.subplot(gs[0])
sns.heatmap(df_heatmap_zscore, cmap='coolwarm', annot=True, cbar=False)
plt.title('Heatmap without t-test and p-value')

# Heatmap for t-test p-values
ax2 = plt.subplot(gs[1])
sns.heatmap(df[['t test', 'p value']], cmap='viridis', annot=True, fmt=".4f", cbar=False, ax=ax2)
plt.title('Heatmap for t-test p-values')

# Create a single colorbar for the z-score
cbar_ax1 = plt.subplot(gs[2])
cbar1 = plt.colorbar(ax1.collections[0], cax=cbar_ax1, orientation='vertical')
cbar1.set_label('Z-score')

# Create a single colorbar for the t-test p-values
cbar_ax2 = plt.subplot(gs[3])
cbar2 = plt.colorbar(ax2.collections[0], cax=cbar_ax2, orientation='vertical')
cbar2.set_label('p-value')

plt.tight_layout()
plt.show()

有没有办法将这些热图组合成一个图,使它们看起来是附加的并具有不同的颜色图案和图例栏?任何帮助或建议将不胜感激。谢谢!

python-3.x matplotlib
1个回答
0
投票

对于下图,我使用

fig.add_axes
(而不是
gridspec
)按顺序添加每个轴,因为我更熟悉该方法。

from matplotlib import pyplot as plt
import seaborn as sns

import pandas as pd
import numpy as np

# Example 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)

# Drop the last two columns
df_heatmap = df.iloc[:, :-2]

# Calculate z-scores for the DataFrame
df_heatmap_zscore = (df_heatmap - df_heatmap.mean()) / df_heatmap.std()

# Set up the layout
fig = plt.figure(figsize=(11, 5))
heatmap_width = 0.2
cbar1_left_gap = 0.02
cbar2_left_gap = 0.08
cbar_width = 0.03
start_x = 0

heatmap_kwargs = dict(annot=True, cbar=False, annot_kws={'size': 9})

# Heatmap for the DataFrame excluding t-test and p-value columns
ax1 = fig.add_axes([start_x, 0, heatmap_width, 1])
sns.heatmap(df_heatmap_zscore, cmap='coolwarm', ax=ax1, **heatmap_kwargs)
ax1.set_title('Heatmap without\nt-test and p-value', fontsize=10)
start_x += heatmap_width

# Heatmap for t-test p-values
ax2 = fig.add_axes([start_x, 0, heatmap_width, 1])
sns.heatmap(df[['t test', 'p value']], cmap='viridis', fmt=".4f", ax=ax2, **heatmap_kwargs)
ax2.tick_params(axis='y', left=False, labelleft=False) #no ticks on ax2
ax2.set_title('Heatmap for\nt-test p-values', fontsize=10)
start_x += heatmap_width

#rotate if desired & remove tick marks
[ax.tick_params(axis='x', rotation=45, bottom=False) for ax in [ax1, ax2]]

#Colorbar 1
cax1 = fig.add_axes([start_x + cbar1_left_gap, 0, cbar_width, 1])
cbar1 = plt.colorbar(ax1.collections[0], cax=cax1, orientation='vertical')
cbar1.set_label('Z-score', size=9)
start_x += cbar1_left_gap + cbar_width

#Colorbar 2
cax2 = fig.add_axes([start_x + cbar2_left_gap, 0, cbar_width, 1])
cbar2 = plt.colorbar(ax2.collections[0], cax=cax2, orientation='vertical')
cbar2.set_label('p-value', size=9)
© www.soinside.com 2019 - 2024. All rights reserved.