pythonic生物人

Heatmap or颜色图(Color Image)

本次分享普通热图,节选自👉嫌Matplotlib繁琐?试试Seaborn!

普通热图严格来说不属于热图,而是颜色图(Color Image),其生成过程不涉及数据转换计算,而是将数据简单映射到一个网格矩阵中,然后根据预先指定的颜色序列为网格矩阵中的数据赋予不同的颜色,从而利用颜色深浅来表示数据的大小。

这种普通热图借助于人眼对颜色的敏感度,可以快速发现统计特征(如颜色深浅与数据大小的关系),相比直接观察数据,具有显著优势。

Python seaborn使用heatmap方法实现普通热图。


普通热图-一行代码

sns.heatmap(data=gene)##默认参数,一行代码搞定
Image

普通热图-添加文本

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

sns.set(font_scale=0.8, rc={"font.family": "Songti SC"})
sns.heatmap(
    data=gene,
    annot=True,
    fmt=".2f",  #设置每个格子中注释文本的格式,此处保留两位小数
    cmap=sns.diverging_palette(255, 5, as_cmap=True),
)
plt.xticks(rotation=45)

Image

普通热图-colormap为所欲为

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(font_scale=0.9, rc={"font.family": "Songti SC"})
for ax, cmap, title in zip(axes.ravel(), cmaps, titles):
    sns.heatmap(
        data=gene,
        annot=True,
        cmap=cmap,  # 设置colormap,更多参考上文章节“5.3.1 构建颜色”
        ax=ax)
    ax.set_title(title)
    ax.tick_params(axis='x', rotation=45)

plt.tight_layout()
plt.show()

Image

普通热图-colorbar位置为所欲为

fig, axes = plt.subplots(2, 2, figsize=(14, 12))

locations = ["top", "bottom", "left", "right"]

for loc, ax in zip(locations, axes.ravel()):
    sns.heatmap(
        data=gene,
        xticklabels=False,
        yticklabels=False,
        cbar=True,
        cbar_kws={
            "location": loc,  #设置colorbar位置
            'label': 'ColorbarName',
            "ticks": np.arange(4.5, 8, 0.5),
            "format": "%.2f",
            "pad": 0.03,
        },
        annot=True,
        fmt=".2f",
        annot_kws={
            "fontsize": 8,
            "color": "black"
        },
        cmap=sns.diverging_palette(255, 5, as_cmap=True),
        ax=ax)
    ax.set_title("Location: " + loc)
    ax.tick_params(axis='x', rotation=45)

plt.tight_layout()
plt.show()

Image

上面这个图只是为了展示colorbar可以放到任意位置,无实际意义。


-END-

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

Image

Image

Image

Image

ImageImage

Image