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

如何在ggplotly图表的悬停提示数值前添加美元符号

错误原因

你代码的核心问题是hovertext参数的使用方式不符合ggplotly的参数规则:

  • 直接放在ggplotly()顶层的hovertext不会识别ggplot图层传递的数值变量,该参数本身也不是用来设置ggplot转译后悬停文本格式的正确入参
  • 自定义悬停文本需要先在ggplot的美学映射中定义文本内容,再通过ggplotly的tooltip参数指定读取该映射,或者直接对生成的plotly对象修改悬停模板。

修正方案1:通过ggplot的text映射实现

该方案适配ggplot的原生语法,逻辑更直观:

library(ggplot2)
library(plotly)

p <- ggplot(economics_long, aes(date, value)) +
      geom_line(aes(text = paste0("value: $", round(value, 2)))) +
      facet_wrap(vars(variable), scales = "free_y", ncol = 1, strip.position = "top") +
      theme(strip.background = element_blank(), strip.placement = "outside")

ggplotly(p, tooltip = "text")

修正方案2:修改plotly对象的悬停模板

如果你更习惯用plotly的原生格式符写法,可以用以下方式:

library(ggplot2)
library(plotly)

p <- ggplotly(ggplot(economics_long, aes(date, value)) +
      geom_line() +
      facet_wrap(vars(variable), scales = "free_y", ncol = 1, strip.position = "top") +
      theme(strip.background = element_blank(), strip.placement = "outside"))

# 批量修改所有轨迹的悬停模板
p <- style(p, hovertemplate = "value: $%{y:.2f}<br>")
p

两种方法都可以实现悬停时显示带美元符号、保留两位小数的数值效果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 06:54:04