Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ggplot2 click with boxplot

Tags:

r

ggplot2

shiny

When I click one point in the chart, that point is highlighted as red.

But soon it goes back to black.

Is there any way to hold the selection?

library(shiny)
library(ggplot2)


server <- function(input, session, output) {
  mtcars$cyl = as.character(mtcars$cyl)


  D = reactive({
    nearPoints(mtcars, input$click_1,allRows = TRUE)
  })

  output$plot_1 = renderPlot({
    set.seed(123)
    ggplot(D(),aes(x=cyl,y=mpg)) + 
      geom_boxplot(outlier.shape = NA) + 
      geom_jitter(aes(color=selected_),width=0.02,size=4)+
      scale_color_manual(values = c("black","red"),guide=FALSE)

  })

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

ui <- fluidPage(

  plotOutput("plot_1",click = clickOpts("click_1")),
  verbatimTextOutput("info")

)

shinyApp(ui = ui, server = server)
like image 736
John Avatar asked Oct 18 '22 01:10

John


1 Answers

Okay, my approach is slightly different to Valter's: selected points become red, whilst you can deselect them and they turn back to black.

The key to achieve this effect (or even Valter's answer with 1 selected point) is to use reactiveValues to keep track of the selected points.

library(shiny)
library(ggplot2)


server <- function(input, session, output) {
  mtcars$cyl = as.character(mtcars$cyl)

  vals <- reactiveValues(clicked = numeric())
  observeEvent(input$click_1, {
    # Selected point/points
    slt <- which(nearPoints(mtcars, input$click_1,allRows = TRUE)$selected)

    # If there are nearby points selected:
    #   add point if it wasn't clicked
    #   remove point if it was clicked earlier
    # Else do nothing

    if(length(slt) > 0){
      remove <- slt %in% vals$clicked
      vals$clicked <- vals$clicked[!vals$clicked %in% slt[remove]]
      vals$clicked <- c(vals$clicked, slt[!remove])
    }
  })

  D = reactive({
    # If row is selected return "Yes", else return "No"
    selected <- ifelse(1:nrow(mtcars) %in% vals$clicked, "Yes", "No")
    cbind(mtcars, selected)
  })

  output$plot_1 = renderPlot({
    set.seed(123)
    ggplot(D(),aes(x=cyl,y=mpg)) + 
      geom_boxplot(outlier.shape = NA) + 
      geom_jitter(aes(color=selected),width=0.02,size=4)+
      scale_color_manual(values = c("black","red"),guide=FALSE)
  })

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

ui <- fluidPage(

  plotOutput("plot_1",click = clickOpts("click_1")),
  verbatimTextOutput("info")

)

shinyApp(ui = ui, server = server)
like image 188
GyD Avatar answered Oct 21 '22 06:10

GyD