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

ggplotly中after_stat()与glue()无法协同工作的解决方法

解决ggplotly中glue结合after_stat报错的问题

问题根源

直接写glue::glue('{after_stat(count)}')会报错,是因为glue会在R全局环境中解析内容,无法识别after_stat的特殊语法,且此时stat_bin生成的count变量还未存在。另外,geom_histogram本身不支持text美学,所以会弹出“Ignoring unknown aesthetics: text”警告,但这个警告不影响ggplotly读取text生成tooltip。

解决方案

方法1:用after_stat包裹glue调用

把glue放在after_stat内部,让glue在stat_bin生成变量的环境中执行,就能正确读取count:

library(ggplot2)
library(plotly)
library(glue)

p <- mtcars |> 
  ggplot() + 
  geom_histogram(
    aes(
      x = disp,
      text = after_stat(glue("分组计数: {count}"))
    ),
    bins = 30 # 明确指定分组数,消除默认bins的提示
  )

ggplotly(p, tooltip = "text")

方法2:使用ggplot原生paste函数

如果不想依赖glue,直接用paste在after_stat中拼接文本,同样能识别count:

library(ggplot2)
library(plotly)

p <- mtcars |> 
  ggplot() + 
  geom_histogram(
    aes(
      x = disp,
      text = after_stat(paste("分组计数:", count))
    ),
    bins = 30
  )

ggplotly(p, tooltip = "text")

消除警告(可选)

如果不想看到“Ignoring unknown aesthetics: text”的警告,用suppressWarnings包裹ggplot代码即可:

p <- suppressWarnings(mtcars |> 
  ggplot() + 
  geom_histogram(
    aes(
      x = disp,
      text = after_stat(glue("分组计数: {count}"))
    ),
    bins = 30
  ))

ggplotly(p, tooltip = "text")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 02:45:14