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

R Plotly自定义tooltip文本时%{text}值无法正常显示

解决Plotly堆叠条形图Tooltip显示%{text}而非具体值的问题

问题原因

在Plotly的R实现中,text参数主要用于设置条形上方/内部显示的文本标签,而非供hovertemplate调用的自定义数据字段。直接在hovertemplate中使用%{text}无法正确映射到myvar1的值,因此会显示原始占位符文本。

解决方案

使用customdata参数传递自定义数据,再在hovertemplate中通过%{customdata}引用该字段。如果需要保留条形上的文本标签,可以同时保留text参数并指定textposition。

修改后的代码

library(plotly)
dfcom <- data.frame(
  myvar1 = c("Media", "Campaigns", "Website"),
  alcance = c(6814511L, 400000L, 225329L),
  type = c("viewers", "viewers", "viewers"))
plot_ly(
  dfcom,
  x = ~alcance, y = ~type,
  # 用customdata传递自定义数据供hover使用
  customdata = ~myvar1,
  # 若需要显示条形文本,保留text并设置textposition
  text = ~myvar1,
  textfont = list(color = I("white")),
  textposition = "inside", # 指定文本显示位置
  type = 'bar',
  color = ~myvar1,
  colors = c("chartreuse4", "darkolivegreen", "darkgreen"),
  showlegend = FALSE,
  # 在hovertemplate中引用customdata
  hovertemplate = "%{x:,.0f} people reached by %{customdata} <extra></extra>") %>%
  layout(barmode = "stack")

关键改动说明

  • 新增customdata = ~myvar1:将myvar1的值作为自定义数据传递给Plotly,供hover模板调用。
  • 修改hovertemplate中的%{text}为%{customdata}:正确引用自定义数据字段。
  • 可选添加textposition = "inside":确保条形上的文本正常显示(如果不需要条形文本,可删除text和textfont相关参数)。

内容的提问来源于stack exchange,提问作者Gonzalo T F

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 05:18:17