上期链接:单细胞UMAP图还能画成“山脉”?Python复刻论文同款3D密度图,附2D版完整代码

上一期我们用Python把单细胞UMAP画成了“山峦”。[1]这次不换数据,换成R语言再做一遍:一张3D密度景观图,一张2D密度等高线图。继续使用GSE226314处理后的Seurat对象[2]。如果用自己的数据,只需提前准备包含数据降维结果和细胞类群注释的单细胞Seurat文件。

01 3D版:让UMAP“长出山峰”

用KernSmooth计算联合核密度(KDE),再用plot3D绘制山体。密度越集中的位置,山峰越高;不同细胞群通过山脚配色和标签区分。

完整代码①|R语言3D UMAP密度山峦图

修改Seurat对象的名称与setwd()路径即可使用;脚本输出PNG和PDF。

#安装并加载R包
for (p in c("SeuratObject", "KernSmooth", "plot3D")) if (!requireNamespace(p, quietly = TRUE)) install.packages(p, repos = "https://cloud.r-project.org", quiet = TRUE)
suppressPackageStartupMessages({library(SeuratObject); library(KernSmooth); library(plot3D); library(grid)})
#设置工作路径与随机数种子
setwd("")
set.seed(123)
#读取数据与设置输出路径
obj <- readRDS("GSE226314_global.rds")
celltype_col <- "cell.type"
outdir <- "./Plots/KDEplot"
dir.create(outdir, recursive = TRUE, showWarnings = FALSE)
#细胞类型配色与标签
style <- data.frame(
  type = c("Adipocyte", "Cardiomyocyte", "Endocardium", "Endothelium", "Epicardium", "Fibroblast", "Glia", "Lymphatic", "Mast", "Myeloid", "Pericyte", "SMC", "TNKCells"),
  color = c("#1f77b4", "#d62728", "#8c564b", "#a23bec", "#e377c2", "#2ca25f", "#ff9896", "#20b2c9", "#ffbb78", "#aec7e8", "#c49c94", "#f2a2c4", "#ddd76d"),
  label = c("Adipocytes", "Cardiomyocytes", "Endocardium", "Endothelial cells", "Epicardium", "Fibroblasts", "Glia", "Lymphatics", "Mast cells", "Myeloid", "Pericytes", "Smooth muscle", "T/NK cells")
)
ct_colors <- setNames(style$color, style$type)
ct_labels <- setNames(style$label, style$type)
#绘图参数
grid_n <- 540L
bandwidth_fraction <- 0.0035
surface_cut <- 0.010
color_quantile <- 0.99
footprint_factor <- 2.5
footprint_cut <- 0.035
footprint_alpha <- 0.42
mountain_height <- 0.42
theta <- 25
phi <- 42
color_steps <- 22L
background <- "#FFFCF3"
label_fs <- 11
label_offsets <- list()
legend_step <- 0.003
#标签偏移示例:label_offsets <- list(Cardiomyocyte = c(15, -5), Fibroblast = c(-15, 6))
#提取并过滤UMAP与细胞类型
xy <- Embeddings(obj, "umap")[, 1:2, drop = FALSE]
ct <- trimws(as.character(obj[[]][rownames(xy), celltype_col]))
keep <- !is.na(ct) & !tolower(ct) %in% c("", "na", "nan", "none", "<na>") & rowSums(!is.finite(xy)) == 0
xy <- xy[keep, , drop = FALSE]; ct <- ct[keep]; cts <- unique(ct)
span <- apply(xy, 2, function(v) diff(range(v)))
stopifnot(nrow(xy) > 1, all(span > 0), all(cts %in% names(ct_colors)))
#黑红密度色带
stops <- c(0, 0.10, 0.25, 0.40, 0.55, 0.68, 0.78, 0.86, 0.93, 1)
anchors <- c("#F0F8F5", "#DDEFF0", "#B8DCE5", "#8BBCCF", "#6098B4", "#365F86", "#292E52", "#571E45", "#E81D43", "#FF263E")
channels <- col2rgb(anchors) / 255
ramp <- sapply(1:3, function(i) approx(stops, channels[i, ], xout = seq(0, 1, length.out = color_steps))$y)
density_colors <- rgb(ramp[, 1], ramp[, 2], ramp[, 3])
#计算联合KDE
bw <- min(span) * bandwidth_fraction
pad <- pmax(span * 0.04, bw * footprint_factor * 4)
lims <- lapply(1:2, function(i) range(xy[, i]) + c(-pad[i], pad[i]))
kde <- function(points, h) bkde2D(points, bandwidth = rep(h, 2), gridsize = rep(grid_n, 2), range.x = lims)
fit <- kde(xy, bw)
x <- fit$x1; y <- fit$x2
Z <- pmax(fit$fhat, 0)
Z <- Z / (sum(Z) * diff(x)[1] * diff(y)[1])
zmax <- max(Z); base_z <- -zmax * 0.015
vmax <- unname(quantile(Z[Z >= zmax * surface_cut], color_quantile))
#计算基底轮廓与标签位置
footprints <- setNames(lapply(cts, function(g) pmax(kde(xy[ct == g, , drop = FALSE], bw * footprint_factor)$fhat, 0)), cts)
footprint_order <- cts[order(vapply(footprints, function(m) sum(m >= max(m) * footprint_cut), numeric(1)), decreasing = TRUE)]
contours <- lapply(footprints, function(m) contourLines(x, y, m, levels = max(m) * footprint_cut))
positions <- t(vapply(footprints, function(m) {
  ij <- arrayInd(which.max(m), dim(m))
  c(x[ij[1]], y[ij[2]], base_z)
}, numeric(3)))
#缩放山体高度与裁剪低密度区域
zscale <- mountain_height / 1.25 * max(vapply(lims, diff, numeric(1))) / (zmax * 1.08 - base_z)
Zplot <- Z * zscale; Zplot[Z < zmax * surface_cut] <- NA_real_
Zcolor <- pmin(Z, vmax); Zcolor[is.na(Zplot)] <- NA_real_
#绘制彩色基底
draw_base <- function(pmat) {
  for (g in footprint_order) {
    paths <- lapply(contours[[g]], function(v) {
      p <- grDevices::trans3d(v$x, v$y, rep(base_z * zscale, length(v$x)), pmat)
      if (any(!is.finite(c(p$x, p$y)))) stop("基底投影异常:", g)
      if (nrow(unique(data.frame(x = p$x, y = p$y))) < 3) return(NULL)
      cbind(p$x, p$y)
    })
    paths <- Filter(Negate(is.null), paths)
    if (!length(paths)) next
    path <- paths[[1]]
    if (length(paths) > 1) for (j in seq.int(2, length(paths))) path <- rbind(path, c(NA_real_, NA_real_), paths[[j]])
    polypath(path[, 1], path[, 2], col = adjustcolor(ct_colors[g], alpha.f = footprint_alpha), border = NA, rule = "evenodd")
  }
}
#绘制3D山体、标签与色条
draw_3d <- function() {
  oldpar <- par(no.readonly = TRUE); on.exit(par(oldpar))
  par(bg = background, fig = c(0, 0.86, 0, 1), mar = rep(0.5, 4), xpd = NA)

  #山体
  pmat <- persp3D(x = x, y = y, z = Zplot, colvar = Zcolor, col = density_colors,
                  clim = c(0, vmax), breaks = seq(0, vmax, length.out = color_steps + 1),
                  xlim = lims[[1]], ylim = lims[[2]], zlim = c(base_z, zmax * 1.08) * zscale,
                  theta = theta, phi = phi, r = 1e5, d = 1e5, scale = FALSE, expand = 1,
                  border = NA, NAcol = NA, shade = 0, lighting = FALSE, axes = FALSE, box = FALSE,
                  xlab = "", ylab = "", zlab = "", colkey = FALSE, panel.first = draw_base)

  #圆角标签
  lab <- grDevices::trans3d(positions[, 1], positions[, 2], positions[, 3] * zscale, pmat)
  lx <- grconvertX(lab$x, "user", "ndc"); ly <- grconvertY(lab$y, "user", "ndc")
  for (i in seq_along(cts)) {
    g <- cts[i]; offset <- label_offsets[[g]]
    if (is.null(offset)) offset <- c(0, -3)
    tx <- unit(lx[i], "npc") + unit(offset[1], "points")
    ty <- unit(ly[i], "npc") + unit(offset[2], "points")
    tg <- textGrob(ct_labels[g], x = tx, y = ty, gp = gpar(col = "white", fontsize = label_fs))
    grid.roundrect(x = tx, y = ty, width = grobWidth(tg) + unit(7, "points"),
                   height = grobHeight(tg) + unit(6, "points"), r = unit(4, "points"),
                   gp = gpar(fill = adjustcolor(ct_colors[g], alpha.f = 0.88), col = NA))
    grid.draw(tg)
  }

  #分段色条与简洁刻度
  left <- 0.875; bottom <- 0.22; bar_width <- 0.020; bar_height <- 0.56
  grid.rect(x = left + bar_width / 2, y = bottom + (seq_len(color_steps) - 0.5) / color_steps * bar_height,
            width = bar_width, height = bar_height / color_steps, gp = gpar(fill = density_colors, col = NA))
  grid.rect(x = left + bar_width / 2, y = bottom + bar_height / 2,
            width = bar_width, height = bar_height, gp = gpar(fill = NA, col = "#888888", lwd = 0.8))
  ticks <- seq(0, vmax, by = legend_step)
  tick_y <- bottom + ticks / vmax * bar_height
  grid.segments(x0 = left + bar_width, x1 = left + bar_width + 0.004,
                y0 = tick_y, y1 = tick_y, gp = gpar(col = "#555555", lwd = 0.7))
  grid.text(formatC(ticks, format = "f", digits = 3), x = left + bar_width + 0.009,
            y = tick_y, just = "left", gp = gpar(col = "#444444", fontsize = 9))
  grid.text("Probability Density", x = 0.975, y = bottom + bar_height / 2,
            rot = 90, gp = gpar(col = "#333333", fontsize = 11))
  invisible(NULL)
}
#保存3D图像
save_3d <- function() {
  paths <- file.path(outdir, c("UMAP_3D_KDE.png", "UMAP_3D_KDE.pdf"))
  for (i in seq_along(paths)) {
    if (i == 1) png(paths[i], width = 12, height = 9, units = "in", res = 400, bg = background)
    if (i == 2) pdf(paths[i], width = 12, height = 9, bg = background, useDingbats = FALSE)
    id <- dev.cur()
    tryCatch(draw_3d(), finally = dev.off(id))
  }
  cat(paste0("已保存:", normalizePath(paths, winslash = "/")), sep = "\n")
}
#显示并导出3D图像
draw_3d()
save_3d()
R语言生成的3D UMAP密度山峦图
图1|R语言生成的3D UMAP密度山峦图。山体高度与红蓝渐变表示估计概率密度,彩色山脚标示细胞群。

02 2D版:把山峰变成等密度线

2D版本把联合密度铺成热图,同时为每种细胞类型添加彩色等密度线。相较3D视角,更适合直接观察不同细胞群在UMAP上的分布范围。

完整代码②|R语言2D UMAP密度热图

同样基于原有UMAP坐标,不必重新聚类。

#安装并加载R包
if (!requireNamespace("SeuratObject", quietly = TRUE)) install.packages("SeuratObject", repos = "https://cloud.r-project.org", quiet = TRUE)
suppressPackageStartupMessages({library(SeuratObject); library(grid)})
#设置工作路径与随机数种子
setwd("")
set.seed(123)
#读取数据与设置输出路径
obj <- readRDS("GSE226314_global.rds")
celltype_col <- "cell.type"
outdir <- "./Plots/KDEplot"
dir.create(outdir, recursive = TRUE, showWarnings = FALSE)
#细胞类型配色
ct_colors <- c(Adipocyte = "#1f77b4", Cardiomyocyte = "#d62728", Endocardium = "#8c564b", Endothelium = "#a23bec", Epicardium = "#e377c2", Fibroblast = "#2ca25f", Glia = "#ff9896", Lymphatic = "#20b2c9", Mast = "#ffbb78", Myeloid = "#aec7e8", Pericyte = "#c49c94", SMC = "#f2a2c4", TNKCells = "#ddd76d")
#绘图参数
grid_n <- 300L
bandwidth <- 0.75
heat_cut <- 0.015
contour_levels <- c(0.10, 0.25, 0.45, 0.65)
contour_width <- 2
contour_alpha <- 0.8
label_fs <- 12
color_steps <- 22L
background <- "white"
#提取并过滤UMAP与细胞类型
xy <- Embeddings(obj, "umap")[, 1:2, drop = FALSE]
ct <- trimws(as.character(obj[[]][rownames(xy), celltype_col]))
keep <- !is.na(ct) & !tolower(ct) %in% c("", "na", "nan", "none", "<na>") & rowSums(!is.finite(xy)) == 0
xy <- xy[keep, , drop = FALSE]; ct <- ct[keep]; cts <- unique(ct)
span <- apply(xy, 2, function(v) diff(range(v)))
stopifnot(nrow(xy) > 1, all(span > 0), all(cts %in% names(ct_colors)))
#黑红密度色带
stops <- c(0, 0.10, 0.25, 0.40, 0.55, 0.68, 0.78, 0.86, 0.93, 1)
anchors <- c("#F0F8F5", "#DDEFF0", "#B8DCE5", "#8BBCCF", "#6098B4", "#365F86", "#292E52", "#571E45", "#E81D43", "#FF263E")
channels <- col2rgb(anchors) / 255
ramp <- sapply(1:3, function(i) approx(stops, channels[i, ], xout = seq(0, 1, length.out = color_steps))$y)
density_colors <- rgb(ramp[, 1], ramp[, 2], ramp[, 3])
#设置网格与中心坐标
xlim <- range(xy[, 1]) + c(-1, 1) * span[1] * 0.05
ylim <- range(xy[, 2]) + c(-1, 1) * span[2] * 0.05
xedges <- seq(xlim[1], xlim[2], length.out = grid_n + 1L)
yedges <- seq(ylim[1], ylim[2], length.out = grid_n + 1L)
xgrid <- (head(xedges, -1) + tail(xedges, -1)) / 2
ygrid <- (head(yedges, -1) + tail(yedges, -1)) / 2
dx <- diff(xedges)[1]; dy <- diff(yedges)[1]
ix <- findInterval(xy[, 1], xedges, rightmost.closed = TRUE)
iy <- findInterval(xy[, 2], yedges, rightmost.closed = TRUE)
bin_id <- ix + (iy - 1L) * grid_n
#高斯核与零填充平滑
gaussian_kernel <- function(sigma) {
  radius <- floor(3 * sigma + 0.5)
  weights <- exp(-0.5 * (seq.int(-radius, radius) / sigma)^2)
  weights / sum(weights)
}
kernel_x <- gaussian_kernel(bandwidth / dx)
kernel_y <- gaussian_kernel(bandwidth / dy)
smooth_axis <- function(v, kernel) {
  radius <- (length(kernel) - 1L) / 2L
  padded <- c(rep(0, radius), v, rep(0, radius))
  as.numeric(stats::filter(padded, kernel, sides = 2))[seq_along(v) + radius]
}
#二维计数、高斯平滑与归一化
density_2d <- function(ids) {
  H <- matrix(tabulate(bin_id[ids], nbins = grid_n^2), nrow = grid_n)
  Z <- apply(H, 2, smooth_axis, kernel = kernel_x)
  Z <- t(apply(Z, 1, smooth_axis, kernel = kernel_y))
  Z / (sum(Z) * dx * dy)
}
#计算联合密度与标签位置
Z <- density_2d(seq_along(ct))
vmax <- max(Z)
Zshow <- Z; Zshow[Z < vmax * heat_cut] <- NA_real_
ct_density <- setNames(lapply(cts, function(g) density_2d(which(ct == g))), cts)
label_pos <- t(vapply(ct_density, function(m) {
  ij <- arrayInd(which.max(m), dim(m))
  c(xgrid[ij[1]], ygrid[ij[2]])
}, numeric(2)))
#绘制2D热图、等高线与色条
draw_2d <- function() {
  oldpar <- par(no.readonly = TRUE); on.exit(par(oldpar))
  par(bg = background, fig = c(0, 0.85, 0, 1), mar = c(1, 1, 2.5, 0.5), family = "sans", ps = 12)

  #联合密度热图
  plot.new()
  plot.window(xlim = xlim, ylim = ylim, asp = 1, xaxs = "i", yaxs = "i")
  image(xedges, yedges, Zshow, col = density_colors, zlim = c(0, vmax), useRaster = TRUE, add = TRUE)
  title(main = "All cells", cex.main = 1.4, font.main = 2, line = 0.7)

  #联合密度与细胞类型等高线
  contour(xgrid, ygrid, Z, levels = seq(vmax * 0.10, vmax * 0.95, length.out = 10),
          add = TRUE, drawlabels = FALSE, col = adjustcolor("white", alpha.f = 0.22), lwd = 0.4 / 0.75)
  for (g in cts) contour(xgrid, ygrid, ct_density[[g]], levels = max(ct_density[[g]]) * contour_levels,
                         add = TRUE, drawlabels = FALSE, col = adjustcolor(ct_colors[g], alpha.f = contour_alpha),
                         lwd = contour_width / 0.75)

  #白色描边标签
  for (angle in seq(0, 2 * pi, length.out = 9)[-9]) {
    text(label_pos[, 1] + cos(angle) * strwidth("M", cex = label_fs / 12) * 0.035,
         label_pos[, 2] + sin(angle) * strheight("M", cex = label_fs / 12) * 0.035,
         labels = cts, cex = label_fs / 12, font = 2, col = "white")
  }
  text(label_pos[, 1], label_pos[, 2], labels = cts, cex = label_fs / 12, font = 2, col = "#263746")

  #分段色条
  left <- 0.865; bottom <- 0.20; bar_width <- 0.022; bar_height <- 0.60
  grid.rect(x = left + bar_width / 2, y = bottom + (seq_len(color_steps) - 0.5) / color_steps * bar_height,
            width = bar_width, height = bar_height / color_steps, gp = gpar(fill = density_colors, col = NA))
  grid.rect(x = left + bar_width / 2, y = bottom + bar_height / 2,
            width = bar_width, height = bar_height, gp = gpar(fill = NA, col = "#888888", lwd = 0.8))

  #简洁刻度
  ticks <- pretty(c(0, vmax), n = 6)
  ticks <- ticks[ticks >= 0 & ticks <= vmax]
  step <- if (length(ticks) > 1) min(diff(ticks)) else vmax
  digits <- max(3L, -floor(log10(step)))
  if (any(abs(ticks - round(ticks, digits)) > step * 1e-6)) digits <- digits + 1L
  tick_y <- bottom + ticks / vmax * bar_height
  grid.segments(x0 = left + bar_width, x1 = left + bar_width + 0.004,
                y0 = tick_y, y1 = tick_y, gp = gpar(col = "#555555", lwd = 0.7))
  grid.text(formatC(ticks, format = "f", digits = digits), x = left + bar_width + 0.009,
            y = tick_y, just = "left", gp = gpar(col = "#444444", fontsize = 9))
  grid.text("Probability Density", x = 0.975, y = bottom + bar_height / 2,
            rot = 90, gp = gpar(col = "#333333", fontsize = 11))
  invisible(NULL)
}
#保存2D图像
save_2d <- function() {
  paths <- file.path(outdir, c("UMAP_2D_KDE.png", "UMAP_2D_KDE.pdf"))
  for (i in seq_along(paths)) {
    if (i == 1) png(paths[i], width = 10, height = 8, units = "in", res = 600, bg = background, pointsize = 12)
    if (i == 2) pdf(paths[i], width = 10, height = 8, bg = background, pointsize = 12, useDingbats = FALSE)
    id <- dev.cur()
    tryCatch(draw_2d(), finally = dev.off(id))
  }
  cat(paste0("已保存:", normalizePath(paths, winslash = "/")), sep = "\n")
}
#显示并导出2D图像
draw_2d()
save_2d()
R语言生成的2D UMAP密度图
图2|R语言生成的2D UMAP密度图。底图是所有细胞的联合KDE,彩色等密度线对应不同细胞类型。

03 想调效果,先看这几个参数

绘图时可根据需要调整关键参数。3D版中,grid_n控制山体精细程度,数值越大细节越丰富;bandwidth_fraction控制平滑程度,越小山峰越尖锐,越大越平滑;theta和phi分别控制水平旋转和俯视角度。2D版中,bandwidth控制热图平滑程度;contour_levels控制等密度线的位置和数量;heat_cut控制低密度区域的显示范围,数值越大背景越干净。两套代码均支持导出高清PNG和PDF,方便公众号展示及论文排版。

需要注意:这里的“山峰”和热度表示细胞在UMAP嵌入空间的估计密度,不是基因表达量,也不是组织内的真实三维位置。同一份UMAP,用Python或R都能画出自己的“细胞景观”。这次就分享到这里。

参考资料

[1] Yang R, Lu C, Jian Q, et al. HBV-driven expansion of CXCR6+-exhausted T cells and CXCL16+ macrophage interaction: Implications for immunotherapy in HCC. The Innovation 2026;7(6):101274. DOI: 10.1016/j.xinn.2026.101274

[2] Amrute JM, Lai L, Ma P, et al. Defining cardiac functional recovery in end-stage heart failure at single-cell resolution. Nature Cardiovascular Research 2023;2(4):399–416. DOI: 10.1038/s44161-023-00260-8