Chapter 7 Graphics

Exercise 7.6.1

Make a plot with click handle that shows all the data returned in the input.

Solution.

Solution

We can use the allRows argument in nearPoints to see the entire data and add a boolean column that will be true TRUE for the given point (i.e., row) that was clicked.

library(shiny)
library(ggplot2)

ui <- fluidPage(
  plotOutput("plot", click = "plot_click"),
  tableOutput("data")
)

server <- function(input, output, session) {
  output$plot <- renderPlot({
    ggplot(mtcars, aes(wt, mpg)) + geom_point()
  }, res = 96)
  
  output$data <- renderTable({
    nearPoints(mtcars, input$plot_click, allRows = TRUE)
  })
}

shinyApp(ui, server)

Exercise 7.6.2

Make a plot with click, dblclick, hover, and brush output handlers and nicely display the current selection in the sidebar. Plot the plot in the main panel.

Solution.

Solution

We can use the nearPoints function to extract the data from plot_click, plot_dbl, and plot_hover. We need to use the function brushedPoints to extract the points within the plot_brush area.

To ‘nicely’ display the current selection, we will use dataTableOutput.

library(shiny)
library(ggplot2)

# Set options for rendering DataTables.
options <- list(
  autoWidth = FALSE,
  searching = FALSE,
  ordering = FALSE,
  lengthChange = FALSE,
  lengthMenu = FALSE,
  pageLength = 5, # Only show 5 rows per page.
  paging = TRUE, # Enable pagination. Must be set for pageLength to work.
  info = FALSE
)

ui <- fluidPage(
  
  sidebarLayout(
    sidebarPanel(
      width = 6,
      
      h4("Selected Points"),
      dataTableOutput("click"), br(),

      h4("Double Clicked Points"),
      dataTableOutput("dbl"), br(),
      
      h4("Hovered Points"),
      dataTableOutput("hover"), br(),
      
      h4("Brushed Points"),
      dataTableOutput("brush")
    ),
    
    mainPanel(width = 6,
              plotOutput("plot",
                         click = "plot_click",
                         dblclick = "plot_dbl",
                         hover = "plot_hover",
                         brush = "plot_brush")
    )
  )
)

server <- function(input, output, session) {
  
  output$plot <- renderPlot({
    ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point()
  }, res = 96)
  
  output$click <- renderDataTable(
    nearPoints(iris, input$plot_click),
    options = options)
  
  output$hover <- renderDataTable(
    nearPoints(iris, input$plot_hover),
    options = options)
  
  output$dbl <- renderDataTable(
    nearPoints(iris, input$plot_dbl),
    options = options)
  
  output$brush <- renderDataTable(
    brushedPoints(iris, input$plot_brush),
    options = options)
}

shinyApp(ui, server)

Exercise 7.6.3

Compute the limits of the distance scale using the size of the plot.

output_size <- function(id) {
  reactive(c(
    session$clientData[[paste0("output_", id, "_width")]],
    session$clientData[[paste0("output_", id, "_height")]]
  ))
}

Solution.

Solution

Let us use the plot’s width and height to estimate the scale limits for our plot.

To verify that the recommended limits are correct, click around the plot and watch how the distance scale changes on the legend. These values should oscillate between the recommended limits.

Resize the browser’s window to change the width and height reactives.

library(shiny)
library(ggplot2)

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

ui <- fluidPage(
  plotOutput("plot", click = "plot_click"),
  textOutput("width"),
  textOutput("height"),
  textOutput("scale")
)

server <- function(input, output, session) {
  
  # Save the plot's widht and height.
  width <- reactive(session$clientData[["output_plot_width"]])
  height <- reactive(session$clientData[["output_plot_height"]])
  
  # Print the plot's width, the plot's height, and the suggested scale limits.
  output$width <- renderText(paste0("Plot's width: ", width()))
  output$height <- renderText(paste0("Plot's height: ", height()))
  output$scale <- renderText({
    paste0("Recommended limits: (0, ", max(height(), width()), ")")
  })
  
  # Store the distance computed by the click event.
  dist <- reactiveVal(rep(1, nrow(df)))
  
  # Update the dist reactive as needed.
  observeEvent(input$plot_click, {
    req(input$plot_click)
    dist(nearPoints(df, input$plot_click, allRows = TRUE, addDist = TRUE)$dist_)
  })
  
  output$plot <- renderPlot({
    df$dist <- dist()
    ggplot(df, aes(x, y, size = dist)) +
      geom_point()
  })
}

shinyApp(ui, server)