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

Plotly新手求助:如何绘制带悬停数值的分组柱状图

解决你的Plotly分组柱状图+悬停需求

Hey there! Let's walk through getting that hover-enabled grouped bar chart set up with your data in R. First, let's fix up the data format—right now your data is in "wide" format, which isn't the easiest for Plotly to work with for grouped bars. We'll convert it to "long" (tidy) format first, then build the chart.

Step 1: Load required packages

You'll need plotly for the interactive chart, and tidyr to reshape your data into a Plotly-friendly structure:

library(plotly)
library(tidyr)

Step 2: Reshape your data to long format

Your current data frame has each group (A/B/C) as a row, but we need each individual value to have its own row with clear labels for group, category, and value. Let's add those labels and pivot the data:

# Your existing data
A <- c(.32, 1.89, 12.9, 51.85, 29.96)
B <- c(1.06, 2.65, 21.27, 47.34, 27.65)
C <- c(.96, 3.85, 18.32, 51.44, 25.401)
matrixValueData <- as.data.frame(rbind(A, B, C))

# Add group names and convert to long format
tidy_data <- matrixValueData %>%
  mutate(Group = rownames(.)) %>%  # Turn A/B/C into a dedicated column
  pivot_longer(cols = -Group, names_to = "Category", values_to = "Value") %>%
  mutate(Category = factor(Category, levels = paste0("Category ", 1:5)))  # Rename default V1-V5 to clearer labels

Step 3: Build the grouped bar chart with custom hover tooltips

Now we'll use plot_ly to create the interactive chart. We'll enable grouped bars and customize exactly what shows up when you hover over a bar:

plot_ly(tidy_data, 
        x = ~Category, 
        y = ~Value, 
        color = ~Group, 
        type = "bar",
        barmode = "group",  # This makes bars from different groups sit side-by-side
        # Customize hover tooltip content
        hovertemplate = paste(
          "Group: %{color}<br>",
          "Category: %{x}<br>",
          "Value: %{y:.2f}<extra></extra>"
        )) %>%
  layout(title = "Grouped Bar Chart with Hover Details",
         xaxis = list(title = "Category"),
         yaxis = list(title = "Value"),
         legend = list(title = list(text = "Groups")))

What this does:

  • barmode = "group" ensures bars from A/B/C are placed next to each other per category instead of stacked.
  • The hovertemplate lets you control every detail of the hover popup—here we show the group name, category, and value (formatted to 2 decimal places for readability).
  • The <extra></extra> removes the default trace name from the tooltip, keeping it clean and focused on your data.

When you run this code, you'll get an interactive chart where hovering over any bar displays the exact value, its group, and category—exactly what you're looking for!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:11:47