1. 数据准备
import pandas as pd
heatmap_data = pd.read_excel(r"相关性热力图_P值.xlsx")
heatmap_data.head()
![Python 画热力图 带P值 一半的_第1张图片](http://img.e-com-net.com/image/info8/cbd9e4ab91ce41a6bdd3d58f5d084fe7.jpg)
2. 计算相关性
![Python 画热力图 带P值 一半的_第2张图片](http://img.e-com-net.com/image/info8/027d33837d04437a84279e99275b1fc1.jpg)
3. 基本样式
![Python 画热力图 带P值 一半的_第3张图片](http://img.e-com-net.com/image/info8/fe2677e11ffc4fe69ab39bed8c3cca43.jpg)
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)
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. 只画一半
![Python 画热力图 带P值 一半的_第4张图片](http://img.e-com-net.com/image/info8/6e162035a92e4d6f89506b53dcbf8857.jpg)
np.ones(corr_df.shape)
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)
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. 进阶相关性矩阵图(带P值)绘制.
![Python 画热力图 带P值 一半的_第5张图片](http://img.e-com-net.com/image/info8/9ee52846ab3a461782e97024324bb1e9.jpg)
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
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))
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)
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. P值和值都带
![Python 画热力图 带P值 一半的_第6张图片](http://img.e-com-net.com/image/info8/b1d06a5ce1684a359d25c11fabef7b77.jpg)
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
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))
corr_star_annot = pval_star.to_numpy()
corr_star_annot``
import matplotlib.pyplot as plt
from colormaps import parula
from matplotlib.ticker import FormatStrFormatter
corr_labels = heatmap_data.corr().to_numpy()
p_labels = corr_star_annot
shape = corr_labels.shape
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)
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()