7.2 Modifying the plot

  • reactiveVal()
  • reactive()

see more info in chapter 16 Escaping the graph

This is part of the function factories (more info here: Function factories), i.e. a function that makes functions. This is the main difference with reactive(), the reactiveVal() function updates the values. It need to be run in an reactive environment. If you’d like to debug the function you can use browser() inside the app, as we shown before.

val <- reactiveVal(10)
val()

Let’s see the distance between a click and the points: Modifying Size App

set.seed(1014)
df <- data.frame(x = rnorm(100), y = rnorm(100))



ui <- fluidPage(
  plotOutput("plot", click = "plot_click") # comma
)


server <- function(input, output, session) {
  # the reactiveVal function
  dist <- reactiveVal(rep(1, nrow(df)))
  # and the observeEvent calling the reactivity
  observeEvent(input$plot_click,
    dist(nearPoints(df, 
                    input$plot_click, 
                    allRows = TRUE, 
                    addDist = TRUE)$dist_) # this "dist_" gives the distance between the row and the event (in pixels) 
  )

  output$plot <- renderPlot({
    df$dist <- dist()
    ggplot(df, aes(x, y, size = dist)) + 
      geom_point() + 
      # set the limits
      scale_size_area(limits = c(0, 1000), max_size = 10, guide = NULL)
  }, res = 96)
}

# shinyApp(ui,server)

Another example with different colors:

  • initialise the reactiveVal() to a vector of FALSEs
  • use brushedPoints() and | to add any points under the brush to the selection
  • double clicking reset the selection
ui <- fluidPage(
  plotOutput("plot", brush = "plot_brush", dblclick = "plot_reset")
)


server <- function(input, output, session) {
  
  selected <- 
    reactiveVal(rep(FALSE, nrow(mtcars)))
    
    observeEvent(input$plot_brush, {
    brushed <- brushedPoints(mtcars, 
                             input$plot_brush,
                             # "selected_" whether it’s near the click event
                             allRows = TRUE)$selected_   
    selected(brushed | selected())
  })
  
  observeEvent(input$plot_reset, {
    selected(rep(FALSE, nrow(mtcars)))
  })

  output$plot <- renderPlot({
    mtcars$sel <- selected()
    
    ggplot(mtcars, aes(wt, mpg)) + 
      geom_point(aes(colour = sel)) +
      scale_colour_discrete(limits = c("TRUE", "FALSE"))
  }, res = 96)
}

# shinyApp(ui,server)