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

如何用R相关包为dygraph信息框添加数据并仅绘制满意度指标

Hey there! Let's tweak your code to focus only on the satisfaction metric while making sure the answers data is easily visible—either in a hover tooltip or a fixed upper-right info box. Here's how to do it:

Solution: Plot Only satisfaction & Display answers in Dygraph

Option 1: Hover Tooltip + Fixed Upper-Right Info Box

This setup keeps the plot clean (only showing satisfaction) but displays answers both when you hover over a data point and in a persistent upper-right box that updates as you move your mouse:

# Load required libraries
library(data.table)
library(dygraphs)
library(xts)

# Generate dummy data
dates <- data.table(
  dates = seq.Date(as.Date("2017-03-01"), length = 14, by = "month"),
  satisfaction = runif(14, min = 0.1, max = 1),
  answers = runif(14, min = 100, max = 1000)
)

# Convert to xts (keep both variables so we can access answers data)
xts_data <- xts(dates[, .(satisfaction, answers)], 
                order.by = as.POSIXct(dates$dates, format = "%Y-%m-%d"))

# Build the dygraph
dygraph(xts_data[, "satisfaction"], main = "Satisfaction Over Time") %>%
  # Show both metrics in the hover tooltip
  dyTooltip(series = "satisfaction", 
            html = "Satisfaction: {y:.2f}<br>Answers: {data.answers:.0f}",
            showHTML = TRUE) %>%
  # Add a fixed upper-right info box that updates on hover
  dyCallbacks(
    drawCallback = 'function(g) {
      // Clean up existing box if it exists
      var oldBox = document.getElementById("answers-box");
      if (oldBox) oldBox.remove();
      
      // Create the info box
      var box = document.createElement("div");
      box.id = "answers-box";
      box.style.position = "absolute";
      box.style.top = "25px";
      box.style.right = "25px";
      box.style.padding = "8px 12px";
      box.style.background = "#fff";
      box.style.border = "1px solid #ddd";
      box.style.borderRadius = "4px";
      box.style.fontSize = "14px";
      box.style.zIndex = "100";
      box.textContent = "Answers: --";
      
      // Add box to the graph container
      g.graphDiv.appendChild(box);
    }',
    highlightCallback = 'function(event, x, points, dygraph) {
      var box = document.getElementById("answers-box");
      if (points.length > 0) {
        // Update box with current answers value (rounded to whole number)
        var ansVal = points[0].pointData.answers.toFixed(0);
        box.textContent = "Answers: " + ansVal;
      } else {
        box.textContent = "Answers: --";
      }
    }'
  )

Option 2: Static Annotations on the Plot

If you'd rather have the answers values displayed directly near each data point (no hover required), use dyAnnotation():

# Load libraries & generate data (same as above)
library(data.table)
library(dygraphs)
library(xts)

dates <- data.table(
  dates = seq.Date(as.Date("2017-03-01"), length = 14, by = "month"),
  satisfaction = runif(14, min = 0.1, max = 1),
  answers = runif(14, min = 100, max = 1000)
)

xts_data <- xts(dates[, .(satisfaction, answers)], 
                order.by = as.POSIXct(dates$dates, format = "%Y-%m-%d"))

# Create annotations for each answers value
answer_annotations <- lapply(1:nrow(dates), function(i) {
  dyAnnotation(
    x = dates$dates[i],
    text = paste("Ans:", round(dates$answers[i])),
    attachAtBottom = FALSE,
    width = 70,
    cssClass = "annotation-style"
  )
})

# Build the graph with annotations
dygraph(xts_data[, "satisfaction"], main = "Satisfaction Over Time") %>%
  dyRangeSelector() %>%
  add_annotations(answer_annotations)

Quick Notes:

  • In Option 1, we keep both variables in the xts object so we can access answers for display, but only plot satisfaction to keep the graph focused.
  • The tooltip uses formatted HTML to make the data easier to read (rounding satisfaction to 2 decimals and answers to whole numbers).
  • For Option 2, you can adjust the cssClass to style the annotations however you like (e.g., change font size or color).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:50:42