Search code examples
rggplot2shinybrush

R Shiny ggplot brush


How to make the brush work and highlight the selected points as red.

It seems the brushedPoints function is not working properly.

library(shiny)
library(ggplot2)


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

  D = reactive({
    brushedPoints(mtcars,input$brush_1, allRows = TRUE)
  })

  output$Plot = renderPlot({
    set.seed(1)
    X = D()
    X[,"cyl"] = as.character(X[,"cyl"])

    ggplot(X,aes_string(x="cyl",y="mpg")) + 
      geom_boxplot(outlier.shape = NA) + 
      geom_jitter(aes(color = selected_))+
      scale_color_manual(values = c("black","red"),guide=FALSE)

  })

  output$log = renderPrint({
    input$brush_1
  })

  output$Data = renderPrint({
    D()
  })
}

ui <- fluidPage(
  plotOutput("Plot",brush = "brush_1"),
  verbatimTextOutput("Data"),
  verbatimTextOutput("log")

)

shinyApp(ui = ui, server = server)

Solution

  • The problem exist because you use different data in brushedPoints and ggplot : convert column to character

    You can try edit data before brushedPoints

    library(shiny)
    library(ggplot2)
    
    
    server <- function(input, session, output) {
      mt=mtcars
      mt[,"cyl"] = as.character(mt[,"cyl"])
      D=reactive({brushedPoints(mt,brush = input$brush_1,  allRows = TRUE)})
    
      output$Plot = renderPlot({
        set.seed(1)
          X <- D()
         ggplot(X,aes_string(x="cyl",y="mpg")) + 
          geom_boxplot(outlier.shape = NA) + 
          geom_jitter(aes(color = selected_))+
          scale_color_manual(values = c("black","red"),guide=FALSE)
    
      })
    
      output$log = renderPrint({
        input$brush_1
      })
    
      output$Data = renderPrint({
        D()
      })
    }
    
    ui <- fluidPage(
      plotOutput("Plot",brush = "brush_1"),
      verbatimTextOutput("Data"),
      verbatimTextOutput("log")
    
    )
    
    shinyApp(ui = ui, server = server)
    

    PS

    for box plot brush work not plain , because all x-coordinates - discrete you can select it only if select middle of box ( point placed not in real position but shifted to left or right - because of geom_jitter)

    As told here there is no way to use geom_jitter and brush