首页 > 解决方案 > plotly - 在散点图中闪亮添加搜索框和突出显示点

问题描述

我在 Shiny 中构建了一个交互式散点图:

library(survival)
library(survminer)

mtcars <- get(data("mtcars"))
attach(mtcars)

mtcars$OS <- sample(100, size = nrow(mtcars), replace = TRUE)
mtcars$status <- sample(0:1, size = nrow(mtcars), replace = TRUE)

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
                    dashboardHeader(),
                    dashboardSidebar(
                      sidebarMenu(
                        menuItem("Test1", tabName = "test1"),
                        menuItem("Test2", tabName = "test2"),
                        menuItem("Test3", tabName = "test3"),
                      

                        radioButtons("radio", h3("Choose groups"),
                                                 choices = list("Group 1" = 1, "Group 2" = 2,
                                                                "Group 3" = 3),selected = 1),
                        actionButton("action", "Reset")
                      
                      )
                    ),
                    dashboardBody(
                      tabItems(
                        tabItem(tabName = "test1",
                                fluidRow(
                                         column(6,plotlyOutput("plot")),
                                         column(width = 6, offset = 0,
                                                DT::dataTableOutput("brush"),
                                                tags$head(tags$style("#brush{font-size:11px;}")))
                                )
                        )
                      )
                    )
)



server <- shinyServer(function(input, output, session) {
  
  output$plot <- renderPlotly({
    key <- row.names(mtcars)
    p <- ggplot(data=mtcars, aes(x=wt,y=mpg,key=key)) +
      geom_point(colour="grey", size=2, alpha=1, stroke=0.5)
    ggplotly(p) %>% layout(height = 500, width = 500, dragmode = "select")
  })
  
  output$brush <- DT::renderDataTable({
    d <- event_data("plotly_selected")
    req(d)
    DT::datatable(mtcars[unlist(d$key), c("mpg", "cyl", "OS", "status")],
                  options = list(lengthMenu = c(5, 30, 50), pageLength = 30))

    }
  )
})

shinyApp(ui, server)

我想在散点图的底部(或顶部)添加一个搜索框。输入样本的 ID 后,相应的点会在散点图上标记。这是我想要实现的图像:

在此处输入图像描述

谢谢,任何帮助都会很棒!

标签: rshinyplotlyhighlightggplotly

解决方案


推荐阅读