如何在Plotly中使用点击获取数据点标签

3
我想在我的Plotly图中点击数据点时存储数据点的标签。该标签是数据帧第一列中出现的数据点名称。
例如,如果我悬停在一个数据点上,它将向我显示x和y信息以及数据点名称:
x:TRUE y:27 Name:cheeseburger 我想要的是将该数据点的标签,“cheeseburger”存储为变量以供以后使用。
我尝试使用plotly_click和访问event_data,但它返回x和y值,而我想要的只是数据点的名称。这是我的代码:

    library(shiny)
    library(plotly)
    
ui <- navbarPage(fluid = TRUE, id = "navbarID",
  theme = shinytheme("superhero"),
  tabsetPanel(type = "tabs",
  tabPanel("File Upload",

  # Sidebar layout with input and output definitions ----
  sidebarLayout(

    # Sidebar panel for inputs ----
    sidebarPanel(

      # Input: Select a file ----
      fileInput("file1", "Choose CSV File",
                multiple = FALSE,
                accept = c("text/csv",
                         "text/comma-separated-values,text/plain",
                         ".csv")),

      # Horizontal line ----
      tags$hr(),

      # Input: Checkbox if file has header ----
      checkboxInput("header", "Header", TRUE),

      # Input: Select separator ----
      radioButtons("sep", "Separator",
                   choices = c(Comma = ",",
                               Semicolon = ";",
                               Tab = "\t"),
                   selected = ","),

      # Input: Select quotes ----
      radioButtons("quote", "Quote",
                   choices = c(None = "",
                               "Double Quote" = '"',
                               "Single Quote" = "'"),
                   selected = '"'),

      # Horizontal line ----
      tags$hr(),

      # Input: Select number of rows to display ----
      radioButtons("disp", "Display",
                   choices = c(Head = "head",
                               All = "all"),
                   selected = "head")

    ),

   
     mainPanel(

      # Output: Data file ----
      tableOutput("contents")

    ),
    
  )  
  ),   
 tabPanel("firstbox", 
 uiOutput("box"),
 
),
    tabPanel("facet_plots",
    mainPanel(plotlyOutput("ind_plot"))
    )    # Main panel for displaying outputs ----
))


# server ----
# Define server logic to plot various variables against 
server <- function(input, output, session) {
  
  
  my_data <- reactive({
    
  inFile <- input$file1
    req(inFile)

    # when reading semicolon separated files,
    # having a comma separator causes `read.csv` to error
    tryCatch(
      {
        df_x <<- read.csv(inFile$datapath,
                 header = input$header,
                 sep = input$sep,
                 quote = input$quote)
       
      },
      error = function(e) {
        # return a safeError if a parsing error occurs
        stop(safeError(e))
      }
    )

    if(input$disp == "head") {
      return(head(df_x))
    }
    else {
      return(df_x)
    } 

    })

  #server logic for file upload tab
   output$contents <- renderTable({
     my_data()

  })

  
  
  #server logic for boxplot tab
  output$box <- renderUI({
   tabPanel("first_box", 
  sidebarPanel(
    selectInput("variable", "Name:", unique(qc$Action)),
    sliderInput("quantile", "Quantile Range:",
      min = 75, max = 95, value = c(85), step = 5),
    br(),
    br(),
  
mainPanel(
    h2("title", align = "center"),
plotlyOutput("plot", height = '1000px', width = "100%")
           )

)
    
    })
    

  observeEvent(input$file1, {
    req(df_x)
    source("db_prep.R")

  
  fn <- reactive(get(paste0("s_", input$quantile)))
  output$plot <-  renderPlotly(fn()(input$variable))
})                        #    ^^^ note the reactive value goes fn()(var)

  
 
     
  s_75 <- function(var) box_75(var) 
  s_80 <- function(var) box_80(var) 
  s_85 <- function(var) box_85(var) 
  s_90 <- function(var) box_90(var)
  s_95 <- function(var) box_95(var)
  m_p <-  function(var) com_g(var)

  
 #Below is that part I am running into trouble
  
  #create reactive for subset plot on second tab
    observeEvent(input$variable, {
    s <- reactive({
    event_data("plotly_click",  source = 'sub_plot')
    })

    
  observeEvent(s(), {
    updateTabsetPanel(session, inputId = "navbarID", selected = "facet_plots")
  })

    output$ind_plot <- renderPlotly({
    req(s())
    
    m_p(s()) # <-- problem here. I need to feed data point label as a string into this function to transform and render new sub plot. 
  })
    
  })

1个回答

2

根据OP的评论更新,每个点的标签是使用geom_text(label())放置并转换为plotly对象

library(shiny)
library(plotly)
library(data.table)

data = data.table(x=1:10, y=sample(1:100, 10)) 
food_labels = sample(c("cheeseburger", "hamburger", "salad", "fries"), 10, replace=T)

get_plotly <- function() {
  ggplotly(ggplot(data,aes(x,y)) + geom_point() + geom_text(label=food_labels))
}

ui <- fluidPage(
  plotlyOutput("plot"),
  verbatimTextOutput(outputId = "clicked_point")
)

server <- function(input, output, session) {
  
  plt <- reactive(get_plotly())
  
  output$plot <- renderPlotly(plt())

  s <- reactive(event_data("plotly_click"))
  
  label_name <- eventReactive(s(), {
    data.table(
      x = plt()$x$data[[2]]$x,
      y = plt()$x$data[[2]]$y,
      text = plt()$x$data[[2]]$text
      )[x==s()$x & y==s()$y, text]
  })
  
  output$clicked_point = renderPrint(label_name())
}

shinyApp(ui, server)

非常感谢您的回答。我已将其标记为正确,因为您提供的代码实现了我在问题中所述的内容,尽管它并没有解决我的具体情况。但这是我没有更清楚地陈述问题的错。我的图已经通过ggplot函数生成,并且我正在尝试访问的标签不在aes中,而是来自geom_text(label =..)扩展。我之前提供的“cheeseburger”值在数据框中,但未用于生成主图,因此我不确定如何将其作为z变量访问。 - Munrock
我稍微调整了一下,给你另一个选项...看看这是否有帮助?请注意,我现在使用ggplot和geom_text创建图形,就像你指示的那样,然后转换为plotly对象。然后我从plotly对象中提取信息... - langtang
这确实让我更接近了,但出现了一个消息,说:“警告:.checkTypos 中的错误:对象“y”在...中未找到。”我认为这与当我用你的代码切换我的数据框时如何访问 data.table 有关。这可能是一个愚蠢的问题,但你能解释一下 data.table 中的 [[2]] 是什么意思吗?我不太确定哪些代码部分应该保持不变,哪些应该用自己的数据框参数替换。 - Munrock
你想要在这里继续吗: https://chat.stackoverflow.com/rooms/242016/room-for-langtang-and-munrock - langtang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接