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

如何仅修改heatmap_of_percentage函数格式化geom_text_contour文本?

问题描述

现有以下最小可复现代码(MWE):

library(metR)

heat_palette = c("darkred", "red", "yellow", "#00A600", "darkgreen")

heatmap_of_percentage <- function(percent) {
  # display <- sprintf("%2f%%", {{percent}})  
  # ^^ 取消注释会触发错误
  c(
    geom_raster(aes(fill = {{percent}})),
    geom_contour(aes(z = {{percent}}), color = "black"),
    geom_text_contour(aes(z = {{percent}}), color = "black", stroke = 0.2),
    scale_fill_gradientn(limits = c(0, 100), colours = heat_palette)
  )
}
  
df <- expand.grid(x = 1:100, y = 1:100)
df$Z <- df$x * df$y / 100

ggplot(df, aes(x = x, y = y)) + 
  heatmap_of_percentage(percent = Z)

上述代码生成的等高线图标签为原始数值,希望将其修改为10%、30%等百分比格式,且仅允许修改heatmap_of_percentage函数,不允许在调用代码中添加额外列,该如何实现?

解决方案

修改heatmap_of_percentage函数,利用after_stat()获取等高线计算后的数值并格式化即可,无需额外处理数据列:

library(metR)
library(rlang)

heat_palette = c("darkred", "red", "yellow", "#00A600", "darkgreen")

heatmap_of_percentage <- function(percent) {
  percent_expr <- enquo(percent)
  c(
    geom_raster(aes(fill = !!percent_expr)),
    geom_contour(aes(z = !!percent_expr), color = "black"),
    geom_text_contour(
      aes(z = !!percent_expr),
      color = "black", 
      stroke = 0.2,
      # 格式化标签为百分比形式,%g自动去除多余小数
      label = sprintf("%g%%", after_stat(z))
    ),
    scale_fill_gradientn(limits = c(0, 100), colours = heat_palette)
  )
}

核心要点:

  • after_stat(z)可以直接获取geom_text_contour内部计算出的等高线数值,避免在函数外修改数据集
  • 若需要固定小数位数,可将sprintf("%g%%", after_stat(z))改为sprintf("%.1f%%", after_stat(z))(保留1位小数)或sprintf("%.2f%%", after_stat(z))(保留2位小数)
  • 使用enquo()和!!操作符确保传入的percent参数能正确在ggplot美学映射中解析

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 19:46:07