Shiny Exercise 6

HTML widgets DT and Plotly

Published

May 5, 2025

Goal: Add Client-Side Interactivity using HTML widgets.

# R packages and setup
library(shiny)
library(DT)
library(plotly)
library(dplyr)
theme_set(theme_minimal())

# data 
data(storms)

storms <- storms |>
  mutate(time = as.POSIXct(paste(year, month, day, hour, sep = "-"),
                           format = "%Y-%m-%d-%H"))

stormsUnique <-  storms |>
  select(name, year) |>
  distinct()


# ui
ui <- fluidPage(
  
  titlePanel("Storm Wind Speed"),
  
  sidebarLayout(
    
    
    sidebarPanel(
      # 1. stormName
      selectInput("stormName",
                  label = "Filter by storm name: ",
                  choices = unique(stormsUnique$name), 
                  selected = stormsUnique$name[[1]])
    ),
    
    mainPanel(
      p("The plot below shows windspeed for the selected storm."),
      
      # 2. windSpeed
      plotOutput("windSpeed")
    )
  )
)

# server
server <- function(input, output, session) {
  
  # 2. windSpeed
  output$windSpeed <- renderPlot({
    
    storms |> 
      filter(name == input$stormName) |>  # 1. stormName
      select(time, wind) |> 
      ggplot(aes(x = time, y = wind)) +
      geom_point(shape = 1, size = 3) + 
      geom_line()
    
  })
  
}

shinyApp(ui, server)
Click to Check the Complete Shiny App Code!
# R packages and setup
library(shiny)
library(DT)
library(plotly)
library(dplyr)
theme_set(theme_minimal())

# data preps
data(storms)

storms <- storms |>
  mutate(time = as.POSIXct(paste(year, month, day, hour, sep = "-"),
                           format = "%Y-%m-%d-%H"))

stormsUnique <-  storms |>
  select(name, year) |>
  distinct()



# ui
ui <- fluidPage(
  
  titlePanel("Storm Wind Speed"),
  
  sidebarLayout(

    sidebarPanel(
      # 1. nameTable
      dataTableOutput("nameTable")
    ),
    
    mainPanel(
      p("The plot below shows windspeed for the selected storm."),
      
      # 2. windSpeed
      plotlyOutput("windSpeed")
    )
  )
)

server <- function(input, output, session) {
  
  # 1. nameTable
  output$nameTable <- renderDataTable({
    stormsUnique
    },
    selection = "single")
  
 
  # 2. windSpeed
  output$windSpeed <- renderPlotly({
    
    str(reactiveValuesToList(input))
    
    req(input$nameTable_row_last_clicked)
    
    stormRow <- slice(stormsUnique, 
                      as.integer(input$nameTable_row_last_clicked))
    
    storms_filtered <- storms |>
      filter(name == stormRow$name & 
             year == stormRow$year) |>
      select(time, wind)
  
    p <- ggplot(storms_filtered, aes(x = time, y = wind)) +
      geom_point(shape = 1, size = 3) + 
      geom_line(color = 'red')
  
    ggplotly(p)
  })
  
}

shinyApp(ui, server)
Back to top