Linking to GEOS 3.13.0, GDAL 3.8.5, PROJ 9.5.1; sf_use_s2() is TRUE
Code
library(ggplot2)library(showtext)
Loading required package: sysfonts
Loading required package: showtextdb
Code
font_add_google("Noto Sans KR", "NotoSansKR")showtext_auto()
2. 대한민국 지도 데이터 사용
Code
# geodata 패키지를 사용하여 대한민국의 GADM 데이터를 다운로드gadm_data <- geodata::gadm("KOR", level =2, path =tempdir())# sf 객체로 변환gadm_sf <-st_as_sf(gadm_data)# 대한민국 지도 시각화ggplot(data = gadm_sf) +geom_sf(fill ="lightblue", color ="black") +ggtitle("대한민국 지도") +theme_minimal()+theme(plot.title =element_text(family ="NotoSansKR", size=20))
Code
# 서울시 데이터 필터링seoul_sf <- gadm_sf[gadm_sf$NAME_1 =="Seoul", ]# 서울시 지도 시각화ggplot(data = seoul_sf) +geom_sf(fill ="lightblue", color ="black") +ggtitle("서울시 지도") +theme_minimal()+theme(plot.title =element_text(family ="NotoSansKR", size=20))
3. rnaturalearth, rnaturalearthdata 사용
Code
#install.packages("rnaturalearth")#install.packages("rnaturalearthdata")install.packages("rnaturalearthhires",repos ="https://ropensci.r-universe.dev") #도시 경계 지도 데이터
The downloaded binary packages are in
/var/folders/vk/xtv6wfd17l95xzkpc62f_k9w0000gn/T//Rtmpad7egp/downloaded_packages
Code
library(rnaturalearth)library(rnaturalearthdata)
Attaching package: 'rnaturalearthdata'
The following object is masked from 'package:rnaturalearth':
countries110
korea <-ne_states(country ="South Korea", returnclass ="sf")ggplot(data = korea) +geom_sf(fill ="lightblue", color ="black") +ggtitle("Seoul, South Korea")
세계지도 그리기
Code
# 국가 데이터 불러오기 (sf 객체로 반환)ne_map <-ne_countries(scale ="small", returnclass ="sf")ne_map_k <-ne_countries(scale ="medium", returnclass ="sf",country ="South Korea")# 지도 그리기ggplot(data = ne_map) +geom_sf(fill ="#FFFFFF", color ="blue") +ggtitle("World Map") #세계
Code
ggplot(data = ne_map_k) +geom_sf(fill ="#FFFFFF", color ="red") +ggtitle("Korea Map") #korea
Code
seoul <- korea[korea$name =="Seoul", ]ggplot(data = seoul) +geom_sf(fill ="lightblue", color ="black") +ggtitle("Seoul, South Korea") #서울시, 해상도 부족
4. leaflet을 사용하여 지도 그리기
웹 기반 인터랙티브 지도 시각화를 가능하게 해주는 도구입니다. 사용자는 위경도 데이터를 기반으로 지도를 생성하고, 다양한 시각적 요소를 추가할 수 있습니다.
Code
#install.packages("leaflet") library(leaflet)leaflet() %>%addTiles() # 기본 OpenStreetMap 타일 추가
기본 지도 로드와 마커 표기
Code
leaflet() %>%addTiles() %>%addMarkers(lng =126.9780, lat =37.5665, popup ="서울 시청")
마커에 인터렉션 제공
Code
library(dplyr)
Attaching package: 'dplyr'
The following objects are masked from 'package:terra':
intersect, union
The following objects are masked from 'package:stats':
filter, lag
The following objects are masked from 'package:base':
intersect, setdiff, setequal, union
Code
places <-data.frame(name =c("서울 시청", "광화문", "경복궁"),lat =c(37.5665, 37.5759, 37.5796),lng =c(126.9780, 126.9770, 126.9771))leaflet(data = places) %>%addTiles() %>%addMarkers(~lng, ~lat, popup =~name) #✔ popup = ~name은 클릭했을 때 이름이 뜨고, label = ~name은 마우스오버 시 이름이 팝업.
Assuming "lng" and "lat" are longitude and latitude, respectively
5. leaflet 지도에 내 데이터 맵핑하기
Code
library(leaflet)library(readr)# 데이터 불러오기wifi <-read_csv("/Users/leehyunjhin/Desktop/R/25_spring/wifi.csv")
Rows: 12290 Columns: 3
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (1): company
dbl (2): lat, lon
ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
Code
# 색상 팔레트 생성: company별 색상 지정pal <-colorFactor(palette ="Set1", domain = wifi$company)# leaflet 지도 생성leaflet(data = wifi) %>%addProviderTiles(providers$CartoDB.Positron) %>%# 지도 스타일 (가볍고 깔끔함)setView(lng =mean(wifi$lon), lat =mean(wifi$lat), zoom =7) %>%addCircleMarkers(~lon, ~lat,color =~pal(company),radius =3,stroke =FALSE,fillOpacity =0.1,label =~company # 마우스오버 시 회사명 표시 ) %>%addLegend("bottomright", pal = pal, values =~company, title ="통신사")
서울시 경계별 컬러를 다르게 표시
Code
library(geodata)library(terra)library(sf)library(dplyr)library(leaflet)library(RColorBrewer)# 1. GADM 레벨 2 데이터 다운로드 (terra 형식 반환됨)korea <-gadm("KOR", level =2, path =tempdir())# 2. terra → sf 변환korea_sf <-st_as_sf(korea)# 3. 서울시 필터링seoul <- korea_sf %>%filter(NAME_1 =="Seoul")# 4. 확인nrow(seoul) # ✅ 25개 안팎이면 정상