热力图(Julia)

作者

[编辑] Bizard 团队

修改于

2026-04-04

🤖 AI Skill — Copy this tutorial's skill into your AI assistant

热力图使用颜色梯度可视化矩阵数据。Julia 的 CairoMakie 提供高性能的热力图渲染,适合大型基因表达矩阵和多组学数据。Makie 生态系统支持注释、聚类和复杂布局,可生成出版级别的图表。

示例

环境配置

  • 系统要求:跨平台(Linux/MacOS/Windows)
  • 编程语言:Julia
  • 依赖包:CairoMakieStatistics
using CairoMakie
using Statistics
using Random

数据准备

Random.seed!(42)
n_genes = 20
n_samples = 10
expr_matrix = randn(n_genes, n_samples)
expr_matrix[1:8, 1:5] .+= 2.5
expr_matrix[9:15, 6:10] .+= 2.0
gene_names = ["Gene_$i" for i in 1:n_genes]
sample_names = ["S$i" for i in 1:n_samples]
10-element Vector{String}:
 "S1"
 "S2"
 "S3"
 "S4"
 "S5"
 "S6"
 "S7"
 "S8"
 "S9"
 "S10"

可视化

基础热力图

fig = Figure(size=(700, 600))
ax = Axis(fig[1,1], xlabel="Samples", ylabel="Genes",
          title="Gene Expression Heatmap",
          xticks=(1:n_samples, sample_names),
          yticks=(1:n_genes, gene_names))
hm = heatmap!(ax, 1:n_samples, 1:n_genes, expr_matrix',
              colormap=:RdBu, colorrange=(-3, 3))
Colorbar(fig[1,2], hm, label="Expression (z-score)")
fig
图 1: 基因表达基础热力图

带注释的热力图

fig2 = Figure(size=(750, 650))
group_ax = Axis(fig2[1,1], height=20, ylabel="",
                xticks=(1:n_samples, sample_names),
                yticks=([1], ["Group"]))
group_colors = vcat(fill(:red, 5), fill(:steelblue, 5))
for i in 1:n_samples
    poly!(group_ax, Rect(i-0.5, 0.5, 1, 1), color=group_colors[i])
end
hidexdecorations!(group_ax)

ax2 = Axis(fig2[2,1], xlabel="Samples", ylabel="Genes",
           xticks=(1:n_samples, sample_names),
           yticks=(1:n_genes, gene_names))
hm2 = heatmap!(ax2, 1:n_samples, 1:n_genes, expr_matrix',
               colormap=:RdBu, colorrange=(-3, 3))
Colorbar(fig2[2,2], hm2, label="Expression")
rowgap!(fig2.layout, 5)
fig2
图 2: 带分组标签的注释热力图

相关矩阵

corr_mat = cor(expr_matrix')
fig3 = Figure(size=(650, 600))
ax3 = Axis(fig3[1,1], xlabel="Gene", ylabel="Gene",
           title="Gene-Gene Correlation",
           xticks=(1:n_genes, gene_names),
           yticks=(1:n_genes, gene_names),
           xticklabelrotation=π/4)
hm3 = heatmap!(ax3, 1:n_genes, 1:n_genes, corr_mat,
               colormap=:coolwarm, colorrange=(-1, 1))
Colorbar(fig3[1,2], hm3, label="Pearson r")
fig3
图 3: 基因-基因相关性热力图

参考文献

  1. Danisch, S., & Krumbiegel, J. (2021). Makie.jl: Flexible high-performance data visualization for Julia. JOSS, 6(65), 3349.