闪亮/绘图:仅使用选定点的标签更新绘图

时间:2019-03-27 10:19:13

标签: r

使用R Shiny并绘制出一个交互式散点图。

如何修改代码以交互地标记用户选择的点?

Example plot

非常感谢您的帮助! 祝一切顺利, 基督徒

library(plotly)
library(shiny)
library(dplyr)

data <- data.frame(matrix(runif(500,0,1000), ncol = 2, nrow = 100)) %>%
  mutate(ID = row_number())

ui <- fluidPage(
  plotlyOutput("plot"),
  verbatimTextOutput("hover"),
  verbatimTextOutput("click"),
  verbatimTextOutput("brush"),
  verbatimTextOutput("zoom"))

server <- function(input, output, session) {

  output$plot <- renderPlotly({
    p <- ggplot(data, aes(x = X1, y = X2, key = ID)) +
      geom_point()
    ggplotly(p) %>% layout(dragmode = "select")
  })
}

shinyApp(ui, server)

1 个答案:

答案 0 :(得分:1)

下面是一个可能的解决方案。我使用反应功能来“标记”所选点。我不确定您要显示所选点的ID的确切程度。当选择一个点时,代码会将ID作为文本添加。另外,我还添加了一些抖动来使ID远离点。

library(plotly)
library(shiny)
library(dplyr)

data <- data.frame(matrix(runif(500,0,1000), ncol = 2, nrow = 100)) %>%
  mutate(ID = row_number())

ui <- fluidPage(
  plotlyOutput("plot"),
  verbatimTextOutput("hover"),
  verbatimTextOutput("click"),
  verbatimTextOutput("brush"),
  verbatimTextOutput("zoom"))

server <- function(input, output, session) {
  output$plot <- renderPlotly({
    data <- get_data()
    p <- ggplot(data, aes(x = X1, y = X2, key = ID)) +
      geom_point() + geom_text(data=subset(data, show_id),aes(X1,X2,label=ID), position = position_jitter(width = 20,height = 20))
    ggplotly(p, source = "subset") %>% layout(dragmode = "select")
  })

  get_data <- reactive({
    event.data <- event_data("plotly_selected", source = "subset")
    data <- data %>% mutate(show_id = FALSE)
    if (!is.null(event.data)) {
      data$show_id[event.data$pointNumber + 1] <- TRUE
    }
    data
  })
}

shinyApp(ui, server)