# Chapter 7 - The same graph, static ({ggplot2}) and interactive ({plotly})
library(shiny)
library(bslib)
library(dplyr)
library(ggplot2)
library(plotly)
library(gapminder)

continents <- levels(gapminder$continent)

ui <- page_sidebar(
  title = "Static or interactive graphs",
  sidebar = sidebar(
    sliderInput("year", "Year", min = 1952, max = 2007, value = 2007, step = 5, sep = ""),
    checkboxGroupInput("continents", "Continents", choices = continents, selected = continents)
  ),
  layout_columns(
    col_widths = c(6, 6),
    card(card_header(code("plotOutput()"), " + ", code("renderPlot()")), plotOutput("scatter")),
    card(card_header(code("plotlyOutput()"), " + ", code("renderPlotly()"), ": hover a point"),
         plotlyOutput("scatter_plotly"))
  )
)

server <- function(input, output, session) {
  filtered <- reactive({
    validate(need(length(input$continents) > 0, "Select at least one continent."))
    gapminder |>
      filter(year == input$year, continent %in% input$continents)
  })

  # Static graph (code of the slide)
  output$scatter <- renderPlot({
    filtered() |>
      ggplot(aes(x = gdpPercap, y = lifeExp)) +
      geom_point() +
      scale_x_log10()
  })

  # Interactive graph (code of the slide): tooltips, zoom, pan
  output$scatter_plotly <- renderPlotly({
    p <- filtered() |>
      ggplot(aes(x = gdpPercap, y = lifeExp,
                 text = country)) +
      geom_point() +
      scale_x_log10()
    ggplotly(p, tooltip = "text")
  })
}

shinyApp(ui, server)
