2016年6月14日 星期二

R 語言資料互動視覺化:Leaflet、Shiny

 

R互動圖表好玩又簡單,不到100行就可以完成網頁前後端,R果然是很人性化的語言啊~




一、Leaflet for R


在R語言中只要載入 library Leaflet (Mobile Friendly Interactive Maps) 就可以很輕鬆的使用 JavaScript Leaflet 做經緯座標的地圖可視化!

下面用政府資料開放平台的古蹟資料展示可視化的效果


R code


leaflet(df_history) %>% 
  addTiles() %>% 
  addCircleMarkers(~lng, ~lat, radius = ~size_check,
                   color = ~RdYlBu(owner), fillOpacity = 0.5)


Result







二、Shiny : 撰寫 R 圖表的簡易前後端


Shiny 讓我們直接用 R 語言撰寫網頁的前後端,Shiny 包含:

  • ui.R — 前端,排版,並內建了各種按鈕元件。
  • server.R — 後端,計算與繪製。

server.R

server <- function(input, output, session) {
  filteredData <- reactive({
    df_history[df_history$years >= input$range[1] & df_history$years <= input$range[2],]
  })
  
  output$map <- renderLeaflet({
    leaflet(df_history) %>% addTiles() %>%
      fitBounds(~min(lng), ~min(lat), ~max(lng), ~max(lat))
  })
  
  observe({
    proxy <- leafletProxy("map", data = df_history)
    proxy %>% clearControls()
    
    if (input$legend) {
      catego <- unique(df_history$owner)
      proxy %>% addLegend(position = "bottomright", colors = RdYlBu(catego),
                          labels = catego
      )
      
      leafletProxy("map", data = filteredData()) %>%
        clearShapes() %>% clearMarkerClusters() %>%
        addCircles(weight = ~size_check,
                   color = ~RdYlBu(owner),
                   opacity = 1,
                   fillOpacity = 1)
      
    }
    else{
      leafletProxy("map", data = filteredData()) %>%
        clearShapes() %>% clearMarkerClusters() %>%
        addMarkers(popup = ~paste("<h5>",name_tw,"</h5>",
                                  years,"年<br>",
                                  address,"<br>"),
                   clusterOptions = markerClusterOptions()) # %>%
      
    }
  })
}


ui.R

library(shiny)
library(leaflet)
library(RColorBrewer)
library(shinythemes)

ui <- bootstrapPage(
  theme = shinytheme("cosmo"),
  title = "Taiwan Historical Map",
  tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
  leafletOutput("map", width = "100%", height = "100%"),
  absolutePanel(top = 100, right = 30,
                draggable = FALSE,
                sliderInput("range", "Years", 1800, 2000,
                            value = c(1800,2000), step = 10
                ),
                checkboxInput("legend", "Show Scatter Diagram", FALSE)
  ),
  absolutePanel(top = 20, right = 42,
                titlePanel(h2("Taiwan Historical Map"))
  )
)



結果如下,可以調整年代範圍即時互動顯示古蹟地理位置與簡介內容。




另外,R Studio 公司有提供的 Shinyapps.io 服務 (platform as a service, PaaS),可以直接將你的shiny app上線!! 非常方便好用^^






References


Creating JavaScript data visualizations in R
https://www.rstudio.com/resources/webinars/creating-javascript-data-visualizations-in-r/

Leaflet for R
https://rstudio.github.io/leaflet/

Codebeautify : 看xml檔結構好用的網站!
http://codebeautify.org/

政府資料開放平台
http://data.gov.tw/

efg's R Notes: RColorBrewer Package
http://earlglynn.github.io/RNotes/package/RColorBrewer/index.html

Shiny Themes
https://rstudio.github.io/shinythemes/

Shinyapps.io
https://www.shinyapps.io/







技術提供:Blogger.