How to change color of one point in a scatter plot on clicking using Shiny and ggplot2

I am trying to find the best way to change the color of one point in a scatter plot by clicking on it. Ultimately I will use this click to create another adjacent plot.

I have figured out a hacky way using global variables but would like to know if there is a better method.
You can see the problem and a working solution here (Shinyappsio).

On the left side, you can see that the color does change momentarily but goes back to the original color. On the right side I avoid this by updating a global variable only when the input$plot_click has a valid input.

It seems that the problem arises from input$plot_click not retaining the value of the last click. Is there a way to make it do that?

Here is the code:


library(tidyverse)
library(shiny)

set.seed(5)

data <- 
  data.frame(x_var = sample(x = 1:100, size = 100), y_var = sample(x = 1:100, size = 100))

ui <- fluidPage(
  fluidRow(
    
    column(width = 6,
           plotOutput("plot_main1", 
                      click = "plot_click1",
                      height = 800
           )
    ),
    column(width = 6,
           plotOutput("plot_main2", 
                      click = "plot_click2",
                      height = 800
           )
    )
  )
)
server <- function(input,output, session){
  output$plot_main1 <- renderPlot({
    Clicked_Point2_Prev <<- data[1,]
    
    plot <- ggplot(data,
                   aes(x_var,y_var)) + 
      geom_point(alpha = 0.5,
                 size = 5,
                 color = "darkblue",
                 stroke = 0)+
      theme(text = element_text(size=20))
    
    
    Clicked_Point1 <- nearPoints(data, input$plot_click1, threshold = 10, maxpoints = 1)
    
    plot <- plot +
      geom_point(data = Clicked_Point1,
                 color = 'red',
                 alpha = 1,
                 size = 5) +
      ggtitle('Click to highlight point not working')
    
    
    plot
    
  }
  )
  
  
  output$plot_main2 <- renderPlot({
    
    
    plot <- ggplot(data,
                   aes(x_var,y_var)) + 
      geom_point(alpha = 0.5,
                 size = 5,
                 color = "darkblue",
                 stroke = 0)+
      theme(text = element_text(size=20))
    
    
    Clicked_Point2 <- nearPoints(data, input$plot_click2, threshold = 10, maxpoints = 1)
    if (length(Clicked_Point2$x_var) > 0) {
      Clicked_Point2_Prev <<- Clicked_Point2
      
    }
    plot <- plot + 
      geom_point(data = Clicked_Point2_Prev,
                 color = 'red',
                 alpha = 1,
                 size = 5)+
    ggtitle('Hacky Fix')
    
    plot
    
  }
  )
}

shinyApp(ui = ui, server = server)
1 Like

I have another question about this. Is using and updating global variables considered to be a bad practice? If yes, why?

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.