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

R语言Plotly的hovertemplate中如何指定额外自定义变量?

R语言Plotly在hovertemplate中添加非x/y/z维度变量的实现方法

问题原因

R版本Plotly的hovertemplate默认仅能识别已映射到绘图核心属性(x、y、z、color等)的字段,未做映射的自定义变量不会被自动加载到悬停模板的解析环境中,直接写%{weight}时程序无法匹配到对应取值,就会直接输出{weight}字符串字面量。

实现步骤

  • 通过customdata参数,把需要在悬停层展示的额外变量传入绘图对象
  • 在hovertemplate中通过%{customdata}引用传入的变量,支持自定义数值显示格式

修正后的可运行代码

library(plotly)
library(tidyverse) 

my_tibble <- tibble(mins = runif(10,10,30),
                     week = 1:10,
                     exercise = c("a", "b", "b", "b", "a", "a", "b", "b", "b", "a"),
                     weight = runif(10,150,160))

example_hex <- c('#70AD47', '#404040', '#CAE1F1', '#24608B')

plot_ly(
  data = my_tibble,
  type = 'bar',
  x = ~week,
  y = ~mins,
  color = ~exercise,
  colors = example_hex,
  # 传入需要额外展示的weight变量
  customdata = ~weight,
  hovertemplate = paste('<b>Week</b>: %{x}<br>',
                        '<b>运动时长</b>: %{y:.0f} 分钟<br>',
                        # 引用customdata传入的weight,.1f表示保留1位小数
                        '<b>体重</b>: %{customdata:.1f}',
                        '<extra></extra>')
)

多变量传入方法

如果需要同时展示多个额外变量,给customdata传入多列数据即可,引用时注意索引从0开始计数:

# 示例:同时传入weight、bodyfat两个变量
plot_ly(
  # 其余基础参数不变
  customdata = ~my_tibble[, c("weight", "bodyfat")],
  hovertemplate = paste('<b>Week</b>: %{x}<br>',
                        '<b>体重</b>: %{customdata[0]:.1f}<br>',
                        '<b>体脂率</b>: %{customdata[1]:.1f}%',
                        '<extra></extra>')
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 11:31:11