Leaflet for R

Page content

1. Introduction

Leaflet 패키지는 동적 지도 시각화를 위한 자바스크립트-오픈소스 기반 라이브러리입니다. 일반적인 기업 회사 뿐만 아니라 GIS 전문 회사인 OpenStreetMap, Mapbox, 그리고 CartoDB에서도 이 패키지를 사용하고 있습니다.

R의 leaflet 패키지는 일종의 자바스크립트의 Leaflet을 쉽게 연동(Integrate) 할 수 있도록 도와 주는 패키지입니다.

2. Features

패키지의 주요 특징은 아래와 같습니다. 오역 방지를 위해 원문에 있는 내용을 그대로 사용했습니다.

  • Interactive panning/zooming

  • Compose maps using arbitrary combinations of:

    • Map tiles
    • Markers
    • Polygons
    • Lines
    • Popups
    • GeoJSON
  • Create maps right from the R console or RStudio

  • Embed maps in knitr/R Markdown documents and Shiny apps

    • R 마크다운과 Shiny Apps에 연동이 쉽게 되는 장점이 있습니다.
    • 이는 보고서 작성 또는 대시보드 작성에 위 패키지를 연동할 수 있는 큰 장점이 있기 때문에 지도 분석과 관련된 업무를 하시는 분에게는 특히 강력히 추천합니다.
  • Easily render spatial objects from the sp or sf packages, or data frames with latitude/longitude columns

  • Use map bounds and mouse events to drive Shiny logic

  • Display maps in non spherical mercator projections

  • Augment map features using chosen plugins from leaflet plugins repository

3. Installation

R 에디터 또는 콘솔창에서는 아래와 같이 입력 후 실행합니다.

install.packages("leaflet")
# to install the development version from Github, run
# devtools::install_github("rstudio/leaflet")

이렇게 한번 설치가 된 이후에는 R마크다운 또는 Shiny앱에서 library(leaflet)을 호출하여 사용할 수 있습니다.

4. Basic Usage

보통 아래와 같은 단계로 사용을 합니다. ggplot2 패키지를 사용하시는 분들은 데이터 + 기하함수 + 설정 등 이러한 형태로 코드를 작성한 기억을 떠올리시면 쉽게 이해가 되실 것입니다.

  • 우선 leaflet() 함수에 데이터프레임을 넣은 후 map 객체를 생성합니다.
  • 그다음 특징에 맞춰서 layer 관련 함수를 추가합니다.
    • addTiles()
    • addMarkers()
    • addPolygons()
  • 각 함수들을 연결할 때에는 Pipe Operator인 R의 강력한 무기인 %>%을 사용합니다.
  • 만약에 %>%인 익숙하지 않다면 magrittr 에서 구체적인 내용을 살펴봅니다.

간단한 그래프를 작성합니다.

library(leaflet)
library(htmlwidgets)
library(htmltools)
library(widgetframe)

m <- leaflet() %>%
  addTiles() %>%  # Add default OpenStreetMap map tiles
  addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")

saveWidget(frameableWidget(m),'leaflet.html')

결과물은 다음을 클릭해서 확인합니다. https://dschloe.github.io/r/leaflet.html

R 강의 소개

Python 강의 소개