如何在闪亮的单个 plotly hovertext 中集成来自多个跟踪的信息

How to integrate information from multiple traces in a singular plotly hovertext in shiny

代码的目的是利用 plotly 创建一个闪亮的应用程序。我们希望每条跟踪线的信息都出现在 x 轴上任何给定点的单个悬停模板中。例如,单个散点图 (mode = 'lines+markers') 中的三个跟踪线,当用户将光标放在单个散点上时,悬停文本会为他们提供三个图中每一个的得分 x-值。

在下面的示例中,我们使用反应函数 Data() 作为一个参与者的数据,该参与者已在服务器端代码的前面进行了子集化。 variable1、variable2 和 variable3 是我们在散点图中绘制的 Data() 的列。与下面的 3 个独立的解决方案相比,没有双重解决方案将具有单一的 hovertext 规范。

我们希望 hovertemplate/hovertext 大致如下所示:

Here are your scores

variable 1 = XXX

variable 2 = XXX

variable 3 = XXX

对于高级点:将鼠标悬停在数据点上时出现的垂直线看起来很棒。

output$distPlot <-  renderPlotly({
  
  
  plot_ly() %>%
    add_trace(                  # trace for variable 1         
      type = 'scatter',
      mode = 'lines+markers',
      x = Data()$Sys.time          # take the time variable from data() for x
      y = Data()$variable1,        # Plot variable1
      hovertemplate = paste(
        "<b>Here are your scores</b><br><br>",
        "variable1: y <br>",
        "variable2: plot2$y <br>",    # placeholder for solution
        "variable3: plot3$y <br>",    # placeholder for solution
        "<extra></extra>"
      ),
      showlegend = TRUE
    ) %>%

       add_trace(                   # trace for variable 2            
      type = 'scatter',
      mode = 'lines+markers',
      x = Data()$Sys.time          # take the time variable from data() for x
      y = Data()$variable2,        # Plot variable2
      hovertemplate = paste(
        "<b>Here are your scores</b><br><br>",
        "variable1: plot1$y <br>",         # Placeholder for solution
        "variable2: y <br>",   
        "variable3: plot3$y <br>",    # Placeholder for solution
        "<extra></extra>"
      ),
      showlegend = TRUE
    ) %>%

    add_trace(                      # trace for variable 3                     
      type = 'scatter',
      mode = 'lines+markers',
      x = Data()$Sys.time          # take the time variable from data() for x
      y = Data()$variable3,        # Plot variable3
      hovertemplate = paste(
        "<b>Here are your scores</b><br><br>",
        "variable1: plot1$y <br>",    # Placeholder for solution
        "variable2: plot2$y <br>",    # Placeholder for solution
        "variable3: y <br>",          
        "<extra></extra>"
      ),
      showlegend = TRUE
    ) 
})      # Close plot

您只需设置 hovermode = 'compare'

这是一个简单的例子:

library(shiny)
library(plotly)

DF <- data.frame(values = c(seq(1, 10, length.out = 10),
                            seq(1, 20, length.out = 10),
                            seq(1, 30, length.out = 10)), variables = rep(LETTERS[1:3], each = 10))

ui <- fluidPage(
plotlyOutput("myPlot")  
)

server <- function(input, output, session) {
  output$myPlot <- renderPlotly({
    plot_ly(DF, y = ~values, color = ~variables, type = "scatter", mode = "lines+markers") %>%
      layout(hovermode = 'compare')
  })
}

shinyApp(ui, server)