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

Plotly中使用add_trace()构建分组柱状图时Hovertemplate冗余内容的去除需求

解决Plotly分组柱状图Hover提示冗余Trace名称的问题

我来帮你搞定这个问题!你看到的白色方框里的LA_ZOO/SF_ZOO是Plotly默认附加在hover提示里的trace名称,属于冗余信息。要移除它很简单,只需要在每个trace的hovertemplate末尾加上<extra></extra>标签——这个标签专门用来控制hover提示中的额外内容,将其留空就能隐藏默认显示的trace名称方框。

以下是修改后的完整代码:

Animals <- c("giraffes", "orangutans", "monkeys")
SF_Zoo <- c(20, 14, 23)
LA_Zoo <- c(12, 18, 29)
data <- data.frame(Animals, SF_Zoo, LA_Zoo)

library(plotly)

fig <- plot_ly(data, 
               x = ~Animals, 
               y = ~SF_Zoo, 
               type = 'bar', 
               name = 'SF_ZOO',
               marker=list(color="#556361"), 
               # 末尾添加<extra></extra>隐藏默认trace名称
               hovertemplate = paste('<b>Animal</b>: %{x}', '<br><b>SF_ZOO</b>: %{y}<br>', '<extra></extra>' ))

fig <- fig %>% add_trace(y = ~LA_Zoo, 
                         name = 'LA_ZOO',
                         marker=list(color="#A72608"), 
                         # 同样添加<extra></extra>
                         hovertemplate = paste('<b>Animal</b>: %{x}', '<br><b>LA_ZOO</b>: %{y}<br>', '<extra></extra>' ))

fig <- fig %>% layout(yaxis = list(title = 'Count'), barmode = 'group')
fig

另外我把你hover提示里的<b>Month</b>改成了<b>Animal</b>,因为你的x轴是动物名称,这样更贴合数据逻辑,如果你确实需要显示Month,可以改回原来的文本~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 05:49:10