geo_data

1. 지도 그리기를 위한 패키지 geodata, sf 설치

Code
#install.packages("geodata") 
#install.packages("sf")

library(geodata)
Loading required package: terra
terra 1.7.78
Code
library(sf)
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
Code
library(rnaturalearthhires)
library(sf)
library(ggplot2)

우리나라 지도 그리기

Code
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은 마우스오버 시 이름이 팝업.

마커 표현 설정

Code
leaflet(data = places) %>%
  addTiles() %>%
  addCircleMarkers(
    ~lng, ~lat,
    radius = 8,
    color = "red",
    fillOpacity = 0.7,
    label = ~name,  # 마우스오버로 이름 보이기
    popup = ~paste0("여기는 ", name, "입니다.")  # 클릭 팝업
  )
Code
leaflet(data = places) %>%
  addTiles() %>%
  addCircleMarkers(
    ~lng, ~lat,
    radius = 8,
    color = "blue",
    stroke = FALSE,
    fillOpacity = 0.7,
    popup = ~name
  ) #radius, color, fillOpacity 등 시각 요소 조절

전국 주요 도시 위치 지도

Code
sample_places <- data.frame(
  name = c("서울", "부산", "대구", "광주", "대전"),
  lat = c(37.5665, 35.1796, 35.8722, 35.1595, 36.3504),
  lng = c(126.9780, 129.0756, 128.6025, 126.8526, 127.3845)
)
leaflet(data = sample_places) %>%
  addTiles() %>%
  addMarkers(~lng, ~lat, popup = ~name)

타일 스타일 변경

Code
leaflet() %>%
  addProviderTiles("CartoDB.Positron") %>%
  setView(lng = 127, lat = 37.5, zoom = 7) #다양한 배경지도: "Stamen.Toner", "Esri.WorldImagery", "CartoDB.DarkMatter" 등
Code
leaflet() %>%
  addProviderTiles("Esri.WorldImagery") %>%
  setView(lng = 127, lat = 37.5, zoom = 7)
Code
leaflet() %>%
  addProviderTiles("CartoDB.DarkMatter") %>%
  setView(lng = 127, lat = 37.5, zoom = 7)

카테고리 값에 따라 마커 색상 다르게 표현

Code
df <- data.frame(
  name = c("서울시청", "경복궁", "강남역", "홍대입구", "잠실야구장"),
  category = c("행정", "관광", "상업", "문화", "스포츠"),
  lat = c(37.5665, 37.5796, 37.4979, 37.5572, 37.5131),
  lng = c(126.9780, 126.9771, 127.0276, 126.9245, 127.0717)
)

color_pal <- colorFactor(
  palette = c("red", "blue", "green", "purple", "orange"),
  domain = c("행정", "관광", "상업", "문화", "스포츠")
)

leaflet(data = df) %>%
  addTiles() %>%
  addCircleMarkers(
    ~lng, ~lat,
    color = ~color_pal(category),
    radius = 7,
    fillOpacity = 0.8,
    popup = ~paste0(name, " (", category, ")")
  ) %>%
  addLegend("bottomright", pal = color_pal, values = ~category, title = "장소 유형")

지도 배율에 따라 마커 표현 변경

Code
leaflet(df) %>%
  addTiles() %>%
  addMarkers(
    ~lng, ~lat,
    clusterOptions = markerClusterOptions()
  )

사용자 제어 레이어 제공

Code
leaflet(df) %>%
  addTiles(group = "기본 지도") %>%
  addProviderTiles("CartoDB.DarkMatter", group = "다크 모드") %>%
  addMarkers(group = "장소") %>%
  addLayersControl(
    baseGroups = c("기본 지도", "다크 모드"),
    overlayGroups = c("장소"),
    options = layersControlOptions(collapsed = FALSE)
  )
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개 안팎이면 정상
[1] 25
Code
# 5. 시각화
n <- length(unique(seoul$NAME_2))
pal <- colorFactor(palette = rainbow(n), domain = seoul$NAME_2)

leaflet(seoul) %>%
  addProviderTiles(providers$CartoDB.Positron) %>%
  addPolygons(
    fillColor = ~pal(NAME_2),
    color = "black",
    label = ~NAME_2,
    fillOpacity = 0.7,
    weight = 1
  ) %>%
  addLegend("bottomright", pal = pal, values = ~NAME_2, title = "서울시 행정구")

서울시 지도에 내 데이터 보여주기

Code
  # 서울시 경계 불러오기
korea <- gadm("KOR", level = 2, path = tempdir())
seoul <- st_as_sf(korea) %>% filter(NAME_1 == "Seoul")

# 와이파이 데이터
wifi <- read_csv("/Users/leehyunjhin/Desktop/R/25_spring/wifi.csv", show_col_types = FALSE)

# sf 변환 + 좌표계 통일
wifi_sf <- st_as_sf(wifi, coords = c("lon", "lat"), crs = st_crs(seoul))

# 서울시 내부 포인트만 필터링
wifi_seoul <- st_join(wifi_sf, seoul, join = st_within) %>% filter(!is.na(NAME_2))

# 확인
print(nrow(wifi_seoul))  # ✅ 0보다 커야 정상
[1] 1072
Code
print(unique(wifi_seoul$company))
[1] "KT"   "LGU+" "SKT" 
Code
# 색상 매핑
pal_wifi <- colorFactor("Set1", domain = unique(wifi_seoul$company))

# 시각화
leaflet() %>%
  addProviderTiles(providers$CartoDB.Positron) %>%
  addPolygons(data = seoul, fillOpacity = 0, color = "black", weight = 1) %>%
  addCircleMarkers(
    data = wifi_seoul,
    radius = 2,
    color = ~pal_wifi(company),
    stroke = FALSE,
    fillOpacity = 0.6,
    popup = ~company
  ) %>%
  addLegend("bottomright", pal = pal_wifi, values = wifi_seoul$company, title = "와이파이 회사")