Try   HackMD
tags: R leaflet Visualization Report 資料視覺化

View Rpubs note on Leaflet套件介紹與範例 (多層互動地圖)
View another note on Leaflet Mini Chart (ShinyApp)
Reference: Leaflet Github

Leaflet功能介紹

  • Tiles: 選擇想要的世界地圖當底圖
  • Marker: 在地圖標上記號
    • 設定經緯度
    • popup: 點擊Marker(r icon::fa_map_marker_alt(color="#F4D03F",size=1))觸發彈出視窗
      • 以html格式呈現
    • label: 感應游標後顯示標籤
    • icon:
leaflet() %>%  # 製作繪圖面板
  setView(lng, lat, zoom) %>%  # 設定視窗範圍 # 以該點放大多少倍
  addTiles() %>%               # 加上底圖
  addMarkers(~lng, ~lat, ~popup, ~label, # 在哪個點上標記號 # 如果不設定經緯度會自己找變數
             icon, clusterOptions = markerClusterOptions()) %>% # 把Marker做Clusters
#### Optional ####
  # 選擇地圖樣式
  addProviderTiles(providers$Stamen.Toner, group = "Toner") %>% 
  # 用範圍圓圈標示
  addCircleMarkers(lng, lat, weight, radius, popup) %>%  # 邊框粗細 # 半徑
  # 使用套件的icon # 替代addMarkers()
  addAwesomeMarkers(lng, lat, icon = awesomeIcons(icon = 'ios-close',
                                                  iconColor = 'black',
                                                  library = 'ion',
                                                  markerColor = getColor(df.20)
                                                 )) %>% 
  # 替代addMarkers(popup)
  addPopups(lng, lat, content, options = popupOptions(closeButton = FALSE)) %>% 
  # 製作Legend
  addLegend("bottomright", pal = colorNumeric(), values, title, opacity = 1) %>% # 調色盤 # 不透明度
  # 製作控制面板
  addLayersControl(
    baseGroups = c("A地圖樣式", "B地圖樣式", "C地圖樣式"), # 前面要設定addTiles(group)和addProviderTiles才可用
    overlayGroups = c("a族群的點", "b族群的點"),
    options = layersControlOptions(collapsed = FALSE)) # 要不要展開layer control # 設F會展開

範例

讀取資料

options(digits=4, scipen=40)
library(dplyr)
library(leaflet)
load("Biz.rdata") # 巴西電商資料 # 188,593 obs.

設定地圖範圍及經緯度

探索資料

table(B$city) %>% sort %>% tail(8) # 前八大城市
rbind(range(B$latitude, na.rm=T), range(B$longitude, na.rm=T)) # 經緯度界線

選擇資料筆數最多的Las Vegas做地圖

B = subset(B, city == "Las Vegas" & !is.na(address) & state == "NV" &  
             B$latitude > 0 & B$longitude > -115.5 & B$longitude < -115) # 28,781 obs.

製作popup

url = "'http://cm.nsysu.edu.tw/~msrc/wp/'"
B$popup = paste(
  sep="<br/>", # 以<br/>換行符號作為分隔
  sprintf("<b><a href=%s>%s</a></b>",url,B$name), # %s: string # 等於:paste0("b><a href=",url,">",B$name,"</a></b>")
  sprintf("Stars:%.1f, Reviews:%d",B$stars,B$review_count), # %.1f: 指定浮點數輸出至小數點以下第一位 # %d: 印整數
  # sprintf("lat:%.2f, lon:%.2f",B$latitude,B$longitude),
  B$address)
B$popup[23677]

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

依據評論數切割資料集

B$review_count %>% cut(c(0,5,10,50,100,200,400,9999)) %>% table # 評論數
B$rank = cut(B$review_count, c(0,5,10,50,100,200,400,9999))     # 評論數屬於哪一個cut
bx = split(B, B$rank)  # 依照評論數的分級切割資料集, 改以list儲存

對每個分割製作地圖物件

l <- leaflet() %>% addTiles() 
# 原始寫法 # 避免使用for loop
names(bx) %>% purrr::walk( function(df) { # 有7個,執行7次
  l <<- l %>% addMarkers(
    data = bx[[df]], lng = ~longitude, lat = ~latitude,
    label = ~name, popup = ~popup, group = df,
    clusterOptions = markerClusterOptions(removeOutsideVisibleBounds=F),
    labelOptions = labelOptions(noHide=F, direction='auto')) 
  })

# for loop寫法(易懂版)
for(i in 1:length(bx)){ 
  l = l %>% addMarkers(
    data = bx[[i]], lng = ~longitude, lat = ~latitude,
    label = ~name, popup = ~popup, group = names(bx)[i],
    clusterOptions = markerClusterOptions(removeOutsideVisibleBounds=F), 
    labelOptions = labelOptions(noHide=F, direction='auto')) 
}

# lapply寫法
z = lapply(1:length(bx), function(i){
  l = l %>% addMarkers(
    data = bx[[i]], lng = ~longitude, lat = ~latitude,
    label = ~name, popup = ~popup, group = names(bx)[i],
    clusterOptions = markerClusterOptions(removeOutsideVisibleBounds=F), 
    labelOptions = labelOptions(noHide=F, direction='auto')) 
})

繪製互動地圖

library(knitr)
l %>% addLayersControl(      # 使用lapply寫法的話,呼叫要指定最後一層: z[[7]]
  overlayGroups = names(bx), 
  options = layersControlOptions(collapsed = FALSE) )

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

You can interact with the map in here

  • addWebGLHeatmap
    可以做出熱圖

  • ~htmlEscape()
    防止html的語法跑掉

Leaflet Extra套件

library(leaflet.extra)

df %>%
  leaflet()%>%
  addTiles()%>%
  addMarkers(label=~Name)%>%
  setView(lng=lng,lat=lat, zoom = 6) %>% 
  addSearchOSM() %>% 
  addReverseSearchOSM() 
  • addSearchOSM()
    打關鍵字就能搜尋其所在位置(類似googlemap的搜尋功能)

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

  • addReverseSearchOSM()
    點擊地圖後回傳的點擊區域的經緯度

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →