pythonic生物人

挑战一行代码搞定Corr Heatmap!

本次分享seaborn 相关性热图代码模版。

节选自教程👉嫌Matplotlib繁琐?试试Seaborn!

相关性热图(Correlation Heatmap)用于展示数据集矩形矩阵中行列变量之间的相关性程度,每个格子中的颜色则表示对应变量相关性程度高低。
seaborn使用heatmap方法实现相关性热图。


相关性热图-一行代码

plt.figure(dpi=150, figsize=(6, 4))
sns.heatmap(
    data=gene.corr(),  #corr函数生成相关矩阵
)
Image

有点丑,没关系,美化一下,


相关性热图-美化1

plt.figure(dpi=120, figsize=(6, 4))

sns.set(font_scale=0.8, rc={"font.family": "Songti SC"})
sns.heatmap(
    data=gene.corr(),
    annot=True,  #开启注释文本
    fmt=".2f",  #设置每个格子中注释文本的格式,此处保留两位小数
    #颜色条美化一下
    cmap=sns.diverging_palette(255, 5, as_cmap=True),
)
plt.xticks(rotation=90)
plt.yticks(rotation=0)
plt.show()

Image

相关性热图-美化2

尝试不同的colormap,

fig, axes = plt.subplots(2, 3, dpi=250, figsize=(25, 15))

titles = ["Diverging", "Greens", "Blues", "PuRd", "YlOrRd", "RdBu_r"]
cmaps = [
    sns.diverging_palette(255, 5, as_cmap=True), "Greens", "Blues", "PuRd",
    "YlOrRd", "RdBu_r"
]

sns.set(rc={"font.family": "Songti SC"})
for ax, cmap, title in zip(axes.ravel(), cmaps, titles):
    sns.heatmap(
        data=gene.corr(method='pearson'),
        annot=True,
        cmap=cmap,  # 设置colormap,更多参考上文章节5.3.1 构建颜色
        ax=ax)

    ax.set_title(title)
    ax.tick_params(axis='x', rotation=90)
    ax.tick_params(axis='y', rotation=0)

plt.tight_layout()
plt.show()、

Image


-END-

更多Python可视化模版(点击图片更精彩)

Image

Image

Image

ImageImage

Image