7.1 Interactivity: the basics

library(shiny)
library(ggplot2)

The syntax for displaying a plot in a Shiny app is:

In the UI the plotOutput() function releases an output that can also be an input.

In the server the renderPlot() function releases the plot.

7.1.1 Summary of interactive action events

  • click
  • dblclick: (double click)
  • hover: (when the mouse stays in the same place for a little while)
  • brush: (a rectangular selection tool)

7.1.1.1 Clicking

As we see in this example, there are two options available:

  • "plot_click"
  • nearPoints()

The first option allows you to select specific points from the data, the other one select the area around the selected point, so it releases values which are near the observed value.

ui <- fluidPage(
  
  plotOutput("plot", click = "plot_click", brush = "plot_brush"),
  verbatimTextOutput("info"),
  tableOutput("data")
  
)

server <- function(input, output, session) {
  
  output$plot <- 
    renderPlot({
    plot(mtcars$wt, mtcars$mpg)
      }, res = 96)
  
  output$info <- 
    renderPrint({
    # this is to make sure the app does nothing before the first click
    req(input$plot_click)
    x <- round(input$plot_click$x, 1)
    y <- round(input$plot_click$y, 1)
    cat("[", x, ", ", y, "]", sep = "")
    })
  
   output$data <- 
     renderTable({
    req(input$plot_click)
    # browser() (you need to use the function with all options as is)
    # nearPoints() function translates coords to data
    nearPoints(mtcars, input$plot_click, xvar = "wt", yvar = "mpg")
    # brushedPoints(mtcars, input$plot_brush, xvar = "wt", yvar = "mpg")
       })
   
    output$data <- 
     renderTable({
    req(input$plot_click)
    
    brushedPoints(mtcars, input$plot_brush, xvar = "wt", yvar = "mpg")
       })
}


# shinyApp(ui,server)

More specific example here : https://gallery.shinyapps.io/095-plot-interaction-advanced/

7.1.1.2 Brushing

  • brush: a rectangular selection

Example of a Brushed Points App

ui <- fluidPage(
  plotOutput("plot", brush = "plot_brush"),
  tableOutput("data")
)
server <- function(input, output, session) {
  output$plot <- renderPlot({
    # here we change the plot() function with ggplot()
    ggplot(mtcars, aes(wt, mpg)) + geom_point()
  }, res = 96)
  
  output$data <- renderTable({
    brushedPoints(mtcars, input$plot_brush)
  })
}