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

R语言ComplexHeatmap热图添加单元格数值报错问题求助

错误根因

你犯了两处语法错误:

  1. 在Heatmap()的参数列表中,给layer_fun传参时错误使用了赋值符号<-,应该使用参数命名符号=
  2. 把grid.text()的坐标、样式参数错误放到了sprintf()的参数列表中,sprintf()仅负责生成要展示的文本内容,坐标、字体等是grid.text()的独立参数

修正后的完整代码

你只需要替换layer_fun部分的代码即可,同时可以新增NA值过滤逻辑,避免空白单元格显示NA:

hmmatrinr <- Heatmap(matrinrmatr, 
                     row_title="Grupos", 
                     column_title="camadas", 
                     col=colheatp, 
                     cluster_rows=FALSE, 
                     cluster_columns=FALSE, 
                     show_column_dend=FALSE, 
                     width=unit(6, "cm"), 
                     height=unit(9, "cm"), 
                     heatmap_legend_param=list(
                       title="Score", 
                       at=c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), 
                       legend_height=unit(8, "cm"), 
                       grid_width=unit(0.5, "cm")
                     ), 
                     # 修正点1:参数赋值用=而不是<-
                     layer_fun = function(j, i, x, y, width, height, fill) {
                       v <- pindex(matrinrmatr, i, j)
                       # 空白单元格不显示NA
                       v[is.na(v)] <- ""
                       # 修正点2:sprintf仅负责生成文本,和grid.text的参数分开
                       grid.text(
                         sprintf("%.2f", v),
                         x = x,
                         y = y,
                         gp = gpar(fontsize = 10, col = "grey")
                       )
                     }
)

额外注意事项

如果运行仍有异常,可以提前将输入数据框转为矩阵,避免pindex识别类型出错:

matrinrmatr <- as.matrix(matrinrmatr)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:06:05