Python draws a heat map with half of the P value

1. Data preparation

import pandas as pd
heatmap_data = pd.read_excel(r"相关性热力图_P值.xlsx")
heatmap_data.head()

insert image description here



2. Calculate the correlation

insert image description here



3. Basic style

insert image description here

from colormaps import parula
from matplotlib.ticker import FormatStrFormatter
import matplotlib.pyplot as plt

fig,ax = plt.subplots(figsize=(4,3.5),dpi=100,facecolor="w")
sns.heatmap(heatmap_data.corr(),annot=True,fmt='.2f',cmap=parula,vmin=-1, vmax=1,
            annot_kws={
    
    "size":7.5,"fontweight":"bold"},linecolor="k",linewidths=.2,
            cbar_kws={
    
    "aspect":13},ax=ax)
ax.yaxis.set_tick_params(labelrotation=0)
# 使用 matplotlib.colorbar.Colorbar object
cbar = ax.collections[0].colorbar
cbar.ax.tick_params(direction="in",width=.5,labelsize=10)
cbar.ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
cbar.outline.set_visible(True)
cbar.outline.set_linewidth(.5)
plt.tight_layout()


4. Only draw half

insert image description here

# 生成形状一样的 1 矩阵
np.ones(corr_df.shape)

# 第k条对角线上方的元素全部置零。k=0(默认值),为主对角线
np.tril(np.ones(corr_df.shape))

mask1 = np.tril(np.ones(corr_df.shape))
lower_triang_df = corr_df.where(np.tril(np.ones(corr_df.shape)).astype(np.bool))
lower_triang_df


fig,ax = plt.subplots(figsize=(4,3.5),dpi=100,facecolor="w")
cor_up = heatmap_data.corr().where(np.triu(np.ones(heatmap_data.corr().shape)).astype(np.bool))
sns.heatmap(cor_up,annot=True,fmt='.2f',cmap=parula,vmin=-1, vmax=1,
            annot_kws={
    
    "size":8,"fontweight":"bold"},linecolor="k",linewidths=.2,
            cbar_kws={
    
    "aspect":13},ax=ax)
ax.yaxis.set_tick_params(labelrotation=0)
# 使用 matplotlib.colorbar.Colorbar object
cbar = ax.collections[0].colorbar
cbar.ax.tick_params(direction="in",width=.5,labelsize=10)
cbar.ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
cbar.outline.set_visible(True)
cbar.outline.set_linewidth(.5)
plt.tight_layout()


5. Drawing of advanced correlation matrix (with P value).

insert image description here

import pandas as pd
import seaborn as sns
import numpy as np

heatmap_data = pd.read_excel(r"相关性热力图_P值.xlsx")
heatmap_data.head()

from scipy.stats import pearsonr
pvals = heatmap_data.corr(method=lambda x, y: pearsonr(x, y)[1]) - np.eye(len(heatmap_data.columns)) 
pvals

#转换P值为星号
def convert_pvalue_to_asterisks(pvalue):
    if pvalue <= 0.001:
        return "***"
    elif pvalue <= 0.01:
        return "**"
    elif pvalue <= 0.05:
        return "*"
    return ""

pval_star = pvals.applymap(lambda x:convert_pvalue_to_asterisks(x))

# 转换成numpy 类型
corr_star_annot = pval_star.to_numpy()
corr_star_annot``
import matplotlib.pyplot as plt
from colormaps import parula
from matplotlib.ticker import FormatStrFormatter

fig,ax = plt.subplots(figsize=(4,3.5),dpi=100,facecolor="w")
sns.heatmap(heatmap_data.corr(),annot=corr_star_annot,fmt='',cmap=parula,vmin=-1, vmax=1,
            annot_kws={
    
    "size":12,"fontweight":"bold"},linecolor="k",linewidths=.2,
            cbar_kws={
    
    "aspect":13},ax=ax)
ax.tick_params(bottom=False, labelbottom=True,labeltop=False,left=False,pad=1,labelsize=12)
ax.yaxis.set_tick_params(labelrotation=0)
# 使用 matplotlib.colorbar.Colorbar object
cbar = ax.collections[0].colorbar
cbar.ax.tick_params(direction="in",width=.5,labelsize=10)
cbar.ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
cbar.outline.set_visible(True)
cbar.outline.set_linewidth(.5)
plt.tight_layout()


6. Both the P value and the value have

insert image description here

import pandas as pd
import seaborn as sns
import numpy as np

heatmap_data = pd.read_excel(r"相关性热力图_P值.xlsx")
heatmap_data.head()

from scipy.stats import pearsonr
pvals = heatmap_data.corr(method=lambda x, y: pearsonr(x, y)[1]) - np.eye(len(heatmap_data.columns)) 
pvals

#转换P值为星号
def convert_pvalue_to_asterisks(pvalue):
    if pvalue <= 0.001:
        return "***"
    elif pvalue <= 0.01:
        return "**"
    elif pvalue <= 0.05:
        return "*"
    return ""

pval_star = pvals.applymap(lambda x:convert_pvalue_to_asterisks(x))

# 转换成numpy 类型
corr_star_annot = pval_star.to_numpy()
corr_star_annot``
import matplotlib.pyplot as plt
from colormaps import parula
from matplotlib.ticker import FormatStrFormatter

# 定制label
corr_labels = heatmap_data.corr().to_numpy()
p_labels = corr_star_annot
shape = corr_labels.shape
#合并labels:列表表达式
labels = (np.asarray(["{0:.2f}\n{1}".format(data,p) for data, p in zip(corr_labels.flatten(), p_labels.flatten())])).reshape(shape)
labels

import matplotlib.pyplot as plt
from colormaps import parula
fig,ax = plt.subplots(figsize=(6,5),dpi=100,facecolor="w")
sns.heatmap(heatmap_data.corr(),annot=labels,fmt='',cmap=parula,vmin=-1, vmax=1,
            annot_kws={
    
    "size":7.5,"fontweight":"bold"},linecolor="k",linewidths=.2,
            cbar_kws={
    
    "aspect":13},ax=ax)
ax.tick_params(bottom=False, labelbottom=True,labeltop=False,left=False,pad=1,labelsize=12)
ax.yaxis.set_tick_params(labelrotation=0)
# 使用 matplotlib.colorbar.Colorbar object
cbar = ax.collections[0].colorbar
cbar.ax.tick_params(direction="in",width=.5,labelsize=10)
cbar.ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
cbar.outline.set_visible(True)
cbar.outline.set_linewidth(.5)
plt.tight_layout()

Guess you like

Origin blog.csdn.net/qq_35240689/article/details/128042073