Plotly R中悬停值的固定位置

8ehkhllq  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(71)

是否可以将轨迹值放置在Plotly/R(仅y值)中,悬停在图的角落,或在图上的固定位置,例如以红色突出显示。

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"))

字符串
然后将样式应用于该值,例如较大的字体x1c 0d1x

svgewumm

svgewumm1#

我们可以用一个小的闪亮的应用程序来实现这样的行为:

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)

字符串


的数据

相关问题