Search code examples
rplotlyhover

Fixed position of hover value in Plotly R


Is it possible to place trace values in Plotly/R (y values only) displayed on hover in the corner of the plot, or in a fixed position on the plot e.g. as highlighted in red.

x <- c(1:100)
random_y <- rnorm(100, mean = 0)
data <- data.frame(x, random_y)

plot_ly(data, x = ~x, y = ~random_y, type = 'scatter', mode = 'lines',
               line = list(color = "#000"))

and then apply styling to that value, say larger font enter image description here


Solution

  • We could achieve such a behaviour with a small shiny app:

    library(shiny)
    library(plotly)
    
    ui <- fluidPage(
      plotlyOutput("plot")
    )
    
    server <- function(input, output, session) {
      
      output$plot <- renderPlotly({
        x <- c(1:100)
        random_y <- rnorm(100, mean = 0)
        data <- data.frame(x, random_y)
        
        p <- plot_ly(data, x = ~x, y = ~random_y, type = 'scatter', mode = 'lines',
                     line = list(color = "#000")) %>%
          layout(annotations = list(
            x = 1, y = 2,
            text = "", # Initialize with empty text
            showarrow = FALSE,
            xanchor = 'left',
            yanchor = 'bottom',
            font = list(
              family = "Arial, sans-serif",
              size = 16,      
              color = "red" 
            )
          ))
        p
      })
      
      observeEvent(event_data("plotly_hover"), {
        hover_data <- event_data("plotly_hover")
        plotlyProxy("plot", session) %>%
          plotlyProxyInvoke("relayout", list(
            annotations = list(
              list(
                x = 1, y = 2,
                text = paste("Y-value:", hover_data$y),
                showarrow = FALSE,
                xanchor = 'left',
                yanchor = 'bottom',
                font = list(
                  family = "Arial, sans-serif",
                  size = 20,      
                  color = "red"   
                )
              )
            )
          ))
      })
    }
    
    shinyApp(ui, server)
    
    

    enter image description here