大規模槍擊事件

使用 R 的 Shiny 建立網頁應用程式

Ramnath Vaidyanathan

VP of Product Research

探索資料

大規模槍擊事件資料集的前 10 列

使用 R 的 Shiny 建立網頁應用程式

一個應用程式:每起大規模槍擊事件以紅色圓點標示,點擊顯示詳細資訊

使用 R 的 Shiny 建立網頁應用程式

加入 UI

ui <- bootstrapPage(
  theme = shinythemes::shinytheme('simplex'),

leaflet::leafletOutput('map', width = '100%', height = '100%'),
absolutePanel(top = 10, right = 10, id = 'controls',
sliderInput('nb_fatalities', 'Minimum Fatalities', 1, 40, 10),
dateRangeInput('date_range', 'Select Date', "2010-01-01", "2019-12-01"),
)
, tags$style(type = "text/css", " html, body {width:100%;height:100%} #controls{background-color:white;padding:20px;} ")
)
使用 R 的 Shiny 建立網頁應用程式

加入輸出:互動式地圖

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

output$map <- leaflet::renderLeaflet({
leaflet() %>%
addTiles() %>%
setView( -98.58, 39.82, zoom = 5)
})
}
使用 R 的 Shiny 建立網頁應用程式

一個含美國互動地圖的應用程式,並可選日期範圍與死亡人數

使用 R 的 Shiny 建立網頁應用程式

加入反應式運算式

rval_mass_shootings <- reactive({

mass_shootings %>%
filter(
date >= input$date_range[1],
date <= input$date_range[2],
fatalities >= input$nb_fatalities
)
})
使用 R 的 Shiny 建立網頁應用程式

更新輸出:互動式地圖

output$map <- leaflet::renderLeaflet({

rval_mass_shootings() %>%
leaflet() %>% addTiles() %>% setView( -98.58, 39.82, zoom = 5) %>%
addCircleMarkers(
popup = ~ summary,
radius = ~ fatalities,
fillColor = 'red', color = 'red', weight = 1
)
})
使用 R 的 Shiny 建立網頁應用程式

一個應用程式:每起大規模槍擊事件以紅色圓點標示,點擊顯示詳細資訊

使用 R 的 Shiny 建立網頁應用程式

更新應用程式:加入動作按鈕與對話框

ui <- bootstrapPage(
  theme = shinythemes::shinytheme('simplex'),
  leaflet::leafletOutput('map', width = '100%', height = '100%'),
  absolutePanel(top = 10, right = 10, id = 'controls',
    sliderInput('nb_fatalities', 'Minimum Fatalities', 1, 40, 10),
    dateRangeInput('date_range', 'Select Date', "2010-01-01", "2019-12-01"),

actionButton('show_about', 'About')
) )
server <- function(input, output, session){

observeEvent(input$show_about, {
showModal(modalDialog(text_about, title = 'About'))
})
}
使用 R 的 Shiny 建立網頁應用程式

一個應用程式:每起大規模槍擊事件以紅色圓點標示,點擊顯示詳細資訊

使用 R 的 Shiny 建立網頁應用程式

一起來練習吧!

使用 R 的 Shiny 建立網頁應用程式

Preparing Video For Download...