You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让ComplexHeatmap的anno_summary/anno_boxplot显示中位数与IQR

解决方法

1. 调整anno_summary显示中位数+IQR

anno_summary默认用均值和标准差,你可以自定义一个统计函数,让它返回中位数和四分位距,再把这个函数传给fun参数即可:

# 自定义统计函数:计算中位数和IQR
median_iqr <- function(x) {
  med <- median(x, na.rm = TRUE)
  iqr_val <- IQR(x, na.rm = TRUE)
  c(中位数 = med, IQR = iqr_val)
}

# 替换默认统计逻辑
column_ha <- HeatmapAnnotation(
  "统计指标" = anno_summary(
    data1,
    fun = median_iqr,
    height = unit(4, "cm"),
    gp = gpar(fill = 1:10)
  )
)

2. 关于anno_boxplot的说明

anno_boxplot生成的箱线图本来就默认显示中位数(箱子中间的线)和IQR(箱子的上下边界,对应Q1和Q3),你原来的代码其实已经满足需求。如果想在箱线图旁标注具体数值,可以新增一个文本注释层:

示例:给箱线图添加中位数和IQR的文字标注

# 先计算每列的中位数和IQR
stats <- data.frame(
  中位数 = apply(data1, 2, median, na.rm = TRUE),
  IQR = apply(data1, 2, IQR, na.rm = TRUE)
)
# 把数值拼接成可显示的文本
stats_text <- paste0("中位数: ", round(stats$中位数, 2), "\nIQR: ", round(stats$IQR, 2))

# 组合箱线图和文本注释
column_ha <- HeatmapAnnotation(
  箱线图 = anno_boxplot(
    data1,
    height = unit(3, "cm"),
    gp = gpar(fill = 1:10)
  ),
  统计值 = anno_text(
    stats_text,
    just = "center",
    height = unit(1, "cm")
  )
)

结合你原有代码的完整版本

data1 <- as.data.frame(dati[, c(3:6)])   

# 计算要标注的统计值
stats <- data.frame(
  中位数 = apply(data1, 2, median, na.rm = TRUE),
  IQR = apply(data1, 2, IQR, na.rm = TRUE)
)
stats_text <- paste0("中位数: ", round(stats$中位数, 2), "\nIQR: ", round(stats$IQR, 2))

# 构建注释层
column_ha <- HeatmapAnnotation(
  箱线图 = anno_boxplot(
    data1,
    height = unit(3, "cm"),
    gp = gpar(fill = 1:10)
  ),
  统计值 = anno_text(
    stats_text,
    just = "center",
    height = unit(1, "cm")
  )
)
        
Heatmap(scale(data1), name = "Legend", column_names_rot = 0, 
        cluster_columns = FALSE, column_title = "Drug exposure",
        width = unit(50, "mm"), split = data.frame(tscc = data$tscc),
        row_title = c(">60 days", "<60 days"),
        row_dend_width = unit(2, "cm"),
        bottom_annotation = column_ha)

内容的提问来源于stack exchange,提问作者Agn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 04:41:04