Как получить event_data для кликабельных фрагментов на графике солнечных лучей R plotly - PullRequest
1 голос
/ 30 октября 2019

При использовании пакета plotly R для создания круговой диаграммы солнечных лучей в приложении Shiny пользователь может щелкнуть график для динамического увеличения / уменьшения. Мы бы хотели иметь возможность загрузить некоторые данные для текущего выбранного / центрированного фрагмента.

Однако мы не можем найти эту информацию из всех возможных опций событий. Существуют события наведения, но этого недостаточно, поскольку пользователь может щелкнуть фрагмент, а затем перемещать мышь, чтобы навести курсор на другие фрагменты, не щелкая его.

Событие щелчка с увеличением / уменьшением отсутствует. И нет события ретрансляции. Я думаю, что должно быть какое-то событие js, запущенное с увеличением / уменьшением, но оно не фиксируется с помощью существующей функции eventdata.

Обновление: казалось, что для диаграммы js есть свойство selectedPath, однако я незнаю, как получить доступ к этим данным в Shiny.

Update2: Спасибо за ответ, который решил проблему. Также это оказалось отсутствующей функцией в пакете plotly R, и он был добавлен в самый последний коммит .

1 Ответ

1 голос
/ 05 ноября 2019

В настоящее время plotly_click предоставляет данные только для корня и листьев графика солнечного взрыва. Однако вы можете передать plotly_hover event_data на reactiveVal после щелчка по графику.

Поскольку вы не предоставили ни одного примера, пожалуйста, посмотрите следующее - используйте onclick() из library(shinyjs) дляОбходной путь.

library(plotly)
library(shinyjs)

DF <- structure(list(labels = c("total", "A", "C", "B", "F", "E", "F", 
                                "E", "D", "E", "D", "D", "F", "G", "H", "H", "G", "H", "G", "H", 
                                "H", "G", "I", "G", "I", "H", "G", "I", "I", "G", "G", "I", "H", 
                                "H", "I", "I", "I", "H", "I", "G"),
                     values = c(100L, 36L, 29L,
                                35L, 12L, 14L, 10L, 14L, 8L, 18L, 5L, 10L, 9L, 6L, 5L, 4L, 3L,
                                7L, 4L, 2L, 6L, 3L, 8L, 3L, 2L, 4L, 4L, 4L, 4L, 4L, 3L, 2L, 5L, 
                                5L, 2L, 2L, 1L, 1L, 1L, 5L),
                     parents = c(NA, "total", "total", "total", "total - A", "total - C", "total - C", "total - A",
                                 "total - B", "total - B", "total - C", "total - A", "total - B",
                                 "total - A - F", "total - C - E", "total - C - F", "total - A - E",
                                 "total - A - E", "total - B - D", "total - B - D", "total - B - E",
                                 "total - C - D", "total - B - E", "total - A - D", "total - B - D",
                                 "total - B - F", "total - C - F", "total - A - E", "total - C - E",
                                 "total - B - E", "total - B - F", "total - A - D", "total - A - D",
                                 "total - A - F", "total - B - F", "total - C - F", "total - C - D",
                                 "total - C - D", "total - A - F", "total - C - E"),
                     ids = c(
                       "total", "total - A", "total - C", "total - B", "total - A - F", "total - C - E", 
                       "total - C - F", "total - A - E", "total - B - D", "total - B - E", "total - C - D",
                       "total - A - D", "total - B - F", "total - A - F - G", "total - C - E - H",
                       "total - C - F - H", "total - A - E - G", "total - A - E - H", "total - B - D - G",
                       "total - B - D - H", "total - B - E - H", "total - C - D - G", "total - B - E - I",
                       "total - A - D - G", "total - B - D - I", "total - B - F - H", "total - C - F - G",
                       "total - A - E - I", "total - C - E - I", "total - B - E - G", "total - B - F - G",
                       "total - A - D - I", "total - A - D - H", "total - A - F - H", "total - B - F - I",
                       "total - C - F - I", "total - C - D - I", "total - C - D - H", "total - A - F - I",
                       "total - C - E - G"
                     )), row.names = c(NA,-40L), class = "data.frame")

ui <- fluidPage(
  useShinyjs(),
  plotlyOutput("sunburst"),
  htmlOutput("hoverDataOut"),
  htmlOutput("clickDataOut")
)

server <- function(input, output, session) {
  output$sunburst <- renderPlotly({
    plot_ly(data = DF, source = "sunSource", customdata = ~ids, ids = ~ids, labels= ~labels, parents = ~parents, values= ~values, type='sunburst', branchvalues = 'total')
  })

  hoverData <- reactive({
    currentEventData <- unlist(event_data(event = "plotly_hover", source = "sunSource", priority = "event"))
  })

  clickData <- reactiveVal()

  observe({
    clickData(unlist(event_data(event = "plotly_click", source = "sunSource", priority = "event")))
  })

  onclick(id = "sunburst", expr = {clickData(hoverData())})

  output$hoverDataOut <- renderText({
    paste("Hover data:", paste(names(hoverData()), unlist(hoverData()), sep = ": ", collapse = " | "))
  })

  output$clickDataOut <- renderText({
    paste("Click data:", paste(names(clickData()), unlist(clickData()), sep = ": ", collapse = " | "))
  })

}

shinyApp(ui, server)

Result


Я создал проблему GitHub , чтобы получить дополнительную информацию об этомповедение.

Вас также может заинтересовать это сообщение .


Обновление: После последнего коммита в реакции на это plotly_sunburstclick может использоваться следующим образом:

# install latest r-plotly dev version:
# devtools::install_github("ropensci/plotly")

library(plotly)
library(shinyjs)

DF <- structure(list(labels = c("total", "A", "C", "B", "F", "E", "F", 
                                "E", "D", "E", "D", "D", "F", "G", "H", "H", "G", "H", "G", "H", 
                                "H", "G", "I", "G", "I", "H", "G", "I", "I", "G", "G", "I", "H", 
                                "H", "I", "I", "I", "H", "I", "G"),
                     values = c(100L, 36L, 29L,
                                35L, 12L, 14L, 10L, 14L, 8L, 18L, 5L, 10L, 9L, 6L, 5L, 4L, 3L,
                                7L, 4L, 2L, 6L, 3L, 8L, 3L, 2L, 4L, 4L, 4L, 4L, 4L, 3L, 2L, 5L, 
                                5L, 2L, 2L, 1L, 1L, 1L, 5L),
                     parents = c(NA, "total", "total", "total", "total - A", "total - C", "total - C", "total - A",
                                 "total - B", "total - B", "total - C", "total - A", "total - B",
                                 "total - A - F", "total - C - E", "total - C - F", "total - A - E",
                                 "total - A - E", "total - B - D", "total - B - D", "total - B - E",
                                 "total - C - D", "total - B - E", "total - A - D", "total - B - D",
                                 "total - B - F", "total - C - F", "total - A - E", "total - C - E",
                                 "total - B - E", "total - B - F", "total - A - D", "total - A - D",
                                 "total - A - F", "total - B - F", "total - C - F", "total - C - D",
                                 "total - C - D", "total - A - F", "total - C - E"),
                     ids = c(
                       "total", "total - A", "total - C", "total - B", "total - A - F", "total - C - E", 
                       "total - C - F", "total - A - E", "total - B - D", "total - B - E", "total - C - D",
                       "total - A - D", "total - B - F", "total - A - F - G", "total - C - E - H",
                       "total - C - F - H", "total - A - E - G", "total - A - E - H", "total - B - D - G",
                       "total - B - D - H", "total - B - E - H", "total - C - D - G", "total - B - E - I",
                       "total - A - D - G", "total - B - D - I", "total - B - F - H", "total - C - F - G",
                       "total - A - E - I", "total - C - E - I", "total - B - E - G", "total - B - F - G",
                       "total - A - D - I", "total - A - D - H", "total - A - F - H", "total - B - F - I",
                       "total - C - F - I", "total - C - D - I", "total - C - D - H", "total - A - F - I",
                       "total - C - E - G"
                     )), row.names = c(NA,-40L), class = "data.frame")

ui <- fluidPage(
  useShinyjs(),
  plotlyOutput("sunburst"),
  htmlOutput("hoverDataOut"),
  htmlOutput("clickDataOut")
)

server <- function(input, output, session) {
  output$sunburst <- renderPlotly({
    plot_ly(data = DF, source = "sunSource", customdata = ~ids, ids = ~ids, labels= ~labels, parents = ~parents, values= ~values, type='sunburst', branchvalues = 'total')
  })

  hoverData <- reactive({
    currentEventData <- unlist(event_data(event = "plotly_hover", source = "sunSource", priority = "event"))
  })

  clickData <- reactive({
    currentEventData <- unlist(event_data(event = "plotly_sunburstclick", source = "sunSource", priority = "event"))
  })

  output$hoverDataOut <- renderText({
    paste("Hover data:", paste(names(hoverData()), unlist(hoverData()), sep = ": ", collapse = " | "))
  })

  output$clickDataOut <- renderText({
    paste("Click data:", paste(names(clickData()), unlist(clickData()), sep = ": ", collapse = " | "))
  })

}

shinyApp(ui, server)
...