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

如何格式化Plotly双变量柱状图的悬停文本?

问题描述

我使用R语言的tidyverse、plotly、lubridate和reshape2包处理了如下数据集:

library(tidyverse)
library(plotly)
library(lubridate)
library(reshape2)

year <- c(2000:2004)
variable1 <- c(10, 14, 23, 14, 20)
variable2 <- c(9, 19, 28, 16, 18)

dtf <- data.frame(year, variable1, variable2)
dtf$year <- lubridate::parse_date_time(dtf$year, orders = "%Y")
dtf$year <- as.Date(dtf$year)
p1 <- melt(dtf, id.vars = "year") |> 
  mutate(across("variable", str_replace, "variable1", "Variable 1")) |> 
  mutate(across("variable", str_replace, "variable2", "Variable 2"))

随后绘制双变量柱状图,图表功能正常,但hovertext(悬停文本)格式不符合需求。当前绘图代码如下:

plot_ly(p1, 
       x = ~year, 
       y = ~value, 
       type="bar",
       color=~variable,
       hovertext = ~paste0(year, "<br>", variable, "<br>", value),
       hoverinfo = "text"#,
       #hovertemplate = paste("%Y", "%{y:.2f}", ""))
       )

我期望悬停文本格式为:

Year: 2000
Variable 1
value (2 decimal points)

尝试设置hovertemplate仅能实现部分效果,请问如何达成预期的悬停文本格式?


解决方案

可以通过两种方式实现你想要的悬停文本格式,以下是具体实现:

方法1:自定义hovertext内容

直接在hovertext中拼接符合要求的格式,注意提取年份数字(因为year是Date类型),同时对数值保留两位小数:

plot_ly(p1, 
       x = ~year, 
       y = ~value, 
       type="bar",
       color=~variable,
       hovertext = ~paste0("Year: ", year(year), "<br>", variable, "<br>", sprintf("%.2f", value)),
       hoverinfo = "text"
       )

这里用到lubridate::year()提取年份数字,sprintf("%.2f", value)将数值格式化为两位小数,通过<br>实现换行。

方法2:使用hovertemplate(更推荐)

hovertemplate支持直接调用plotly的变量占位符,自定义文本格式更灵活:

plot_ly(p1, 
       x = ~year, 
       y = ~value, 
       type="bar",
       color=~variable,
       hovertemplate = paste(
         "Year: %{x|%Y}<br>",
         "%{color}<br>",
         "%{y:.2f}<extra></extra>"
       )
       )
  • %{x|%Y}:将x轴的日期格式化为四位年份
  • %{color}:直接调用图例对应的变量名称(即Variable 1/Variable 2)
  • %{y:.2f}:将y轴数值格式化为两位小数
  • <extra></extra>:隐藏plotly默认的额外图例文本,避免冗余

两种方法都能实现目标格式,第二种更符合plotly原生语法,后续维护更方便。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 10:52:18