r4ds / mastering_shiny_book_solutions

https://mastering-shiny-solutions.org
Creative Commons Zero v1.0 Universal
19 stars 6 forks source link

Interpretation of exercise 7.6.3 #44

Open edovt opened 3 years ago

edovt commented 3 years ago

Hello, I was reading the solution to exercise 7.6.3 and I think the idea of the question is different, but I do not know if I am correct. In the end of the first example in 7.1.5, Modifying the plot, it says

I set the limits to scale_size_area() to ensure that sizes are comparable across clicks. To find the correct range I did a little interactive experimentation, but you can work out the exact details if needed (see the exercises at the end of the chapter).

The problem with this is that if one has a big plot, and the distance of one point to the click event is over 1000, the point will disappear, so I think that those details mentioned are the idea of the exercise, which is to modify this code, but instead of using a maximum of 1000, updating it whenever the plot changes to the maximum possible distance in the plot:

library(shiny)
library(ggplot2)

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

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

server <- function(input, output, session) {

  # Store the distance computed by the click event.
  dist <- reactiveVal(rep(1, nrow(df)))

  # Update the dist reactive as needed.
  observeEvent(input$plot_click, {
    dist(nearPoints(df, input$plot_click, allRows = TRUE, addDist = TRUE)$dist_)
  })

  # Save the plot's width and height
  width <- reactive(session$clientData[["output_plot_width"]])
  height <- reactive(session$clientData[["output_plot_height"]])

  # Calculate the maximum distance possible in the plot
  max_limit <- reactive(sqrt(width()^2 + height()^2))

  output$plot <- renderPlot({
    df$dist <- dist()
    ggplot(df, aes(x, y, size = dist)) +
      geom_point() +
      scale_size_area(limits = c(0, max_limit()), max_size = 10)
  })
}

shinyApp(ui, server)