Is there a way to preselect points in ggiraph (R shiny)?

415 Views Asked by At

I would like to preselect some points in a ggiraph::renderggiraph() output.

I can make the following shiny app which allows me to select points and then use those selected points elsewhere like so:

dat <- data.table(x = 1:6, y = 1:6 %% 3, id = 1:6, status = rep(c('on','off'),3))

ui <- fluidPage(   ggiraphOutput("plot"),
                   verbatimTextOutput("choices"))

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


  output$plot <- renderggiraph({
    p <- ggplot(dat ) +
      geom_point_interactive(aes(x = x, y = y, data_id = id), size = 5) + 
      scale_color_manual(limits = c('on','off'),values = c('red','black')) 

    ggiraph(code = print(p),
            hover_css = "fill:red;cursor:pointer;",
            selection_type = "multiple",
            selected_css = "fill:red;")
  })

  output$choices <- renderPrint({

  input$plot_selected
  })


}

shinyApp(ui = ui, server = server)

But sometimes I want to have certain points selected before I initialize the app. For example, if the points 1, 3, and 5 are already "on" orginally, I would like the user to be able to turn them "off".

So my question is, is it possible to achieve something like this?

1

There are 1 best solutions below

3
On BEST ANSWER

Yes, by using session$sendCustomMessage in session$onFlushed:

library(shiny)
library(ggiraph)
library(data.table)
library(magrittr)
dat <- data.table(x = 1:6, y = 1:6 %% 3, id = 1:6, status = rep(c('on','off'),3))

ui <- fluidPage(   fluidRow(
  column(width = 7, 
         ggiraphOutput("ggobj") ),
  column(width = 5, verbatimTextOutput("choices"))
) )

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

  output$ggobj <- renderggiraph({
    p <- ggplot(dat ) +
      geom_point_interactive(aes(x = x, y = y, data_id = id), size = 5) + 
      scale_color_manual(limits = c('on','off'),values = c('red','black')) 

    ggiraph(code = print(p),
            hover_css = "fill:red;cursor:pointer;",
            selection_type = "multiple",
            selected_css = "fill:red;")
  })
  session$onFlushed(function(){
    session$sendCustomMessage(type = 'ggobj_set', message = 1:3)
  })
  output$choices <- renderPrint({
    input$ggobj_selected
  })


}

shinyApp(ui = ui, server = server)