R) ggplot2 - 세계지도

R) ggplot2 - 세계지도

R의 세계지도 관련 패키지를 활용하여 시각화를 해본다.

개요

지도를 시각화 하기 위해서는 일반적으로 shp파일(“shape 파일”로 읽으면 된다.)을 사용하는 경우가 많지만, 대부분의 경우 고정밀 지도가 아닌 대충 모양새만 맞으면 되기 때문에 세계지도를 시각화 할 때는 R에서 제공하는 패키지를 사용하는 경우가 많다.

시각화는 ggplot2 기반으로 진행하기 때문에 미리 불러오도록 하자.

1
library("ggplot2")

rnaturalearth

naturalearth 패키지는 Natural Earth 에서 제공하는 데이터 중 일부를 R에서 사용할 수 있도록 만들어진 패키지이다. 110개 국가의 개략적인 국토 경계선 지도를 제공한다. 좀 더 자세한 내용은 Natural Earth 페이지를 참고하기 바란다.
Natural Earth 메인 페이지

데이터 확인

패키지를 불러와서 데이터를 확인해보자. 지도 데이터를 불러오는 함수는 ne_countries() 함수이고 주요 인자는 다음과 같다.
● continent: 대륙 지정
● country: 나라 지정
● scale: 축척을 설정하며 “small”, “medium”, “large” 중 하나를 선택하여 지도 축척을 결정

단, scale에 “small”이 아닌 다른 축척을 선택할 경우 별도의 패키지를 설치해야 하는데 제대로 설치가 되지 않을 수 있으니 주의한다.

이제 ne_countries() 함수에 지정할 대륙 또는 나라를 확인하기 위해서 다음과 같이 코드를 작성해보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
library("rnaturalearth")
head(countries110@data, 2)
## scalerank featurecla labelrank sovereignt sov_a3 adm0_dif level
## 0 1 Admin-0 country 3 Afghanistan AFG 0 2
## 1 1 Admin-0 country 3 Angola AGO 0 2
## type admin adm0_a3 geou_dif geounit gu_a3 su_dif
## 0 Sovereign country Afghanistan AFG 0 Afghanistan AFG 0
## 1 Sovereign country Angola AGO 0 Angola AGO 0
## subunit su_a3 brk_diff name name_long brk_a3 brk_name
## 0 Afghanistan AFG 0 Afghanistan Afghanistan AFG Afghanistan
## 1 Angola AGO 0 Angola Angola AGO Angola
## brk_group abbrev postal formal_en formal_fr note_adm0
## 0 <NA> Afg. AF Islamic State of Afghanistan <NA> <NA>
## 1 <NA> Ang. AO People's Republic of Angola <NA> <NA>
## note_brk name_sort name_alt mapcolor7 mapcolor8 mapcolor9 mapcolor13
## 0 <NA> Afghanistan <NA> 5 6 8 7
## 1 <NA> Angola <NA> 3 2 6 1
## pop_est gdp_md_est pop_year lastcensus gdp_year
## 0 28400000 22270 NA 1979 NA
## 1 12799293 110300 NA 1970 NA
## economy income_grp wikipedia fips_10 iso_a2
## 0 7. Least developed region 5. Low income NA <NA> AF
## 1 7. Least developed region 3. Upper middle income NA <NA> AO
## iso_a3 iso_n3 un_a3 wb_a2 wb_a3 woe_id adm0_a3_is adm0_a3_us adm0_a3_un
## 0 AFG 004 004 AF AFG NA AFG AFG NA
## 1 AGO 024 024 AO AGO NA AGO AGO NA
## adm0_a3_wb continent region_un subregion region_wb name_len
## 0 NA Asia Asia Southern Asia South Asia 11
## 1 NA Africa Africa Middle Africa Sub-Saharan Africa 6
## long_len abbrev_len tiny homepart
## 0 11 4 NA 1
## 1 6 4 NA 1

rnaturalearth 패키지의 “countries110” 객체는 S4 클래스이기 때문에 “@” 기호를 사용하여 하위 슬롯(slot)에 접근할 수 있으며 “data”슬롯에는 63개의 변수가 있다. “countries110” 객체의 주요 변수는 다음과 같다.
● continent: 특정 국가의 소속 대륙명
● name: 국가명
● name_long: 정식 국가명
● brk_a3: 국가 3 CODE(영문 대문자 3개로 표기)

세계지도 시각화

상기 목록을 참고하여 대상 국가 또는 대륙 데이터를 추출할 수 있으며 별다른 국가명 지정 없이 사용한 결과는 다음과 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
ne_map = ne_countries(scale = "small")
class(ne_map)
## [1] "SpatialPolygonsDataFrame"
## attr(,"package")
## [1] "sp"

slotNames(ne_map)
## [1] "data" "polygons" "plotOrder" "bbox" "proj4string"

df_for = fortify(df)
## Regions defined for each Polygons
head(df_for, 2)
## long lat order hole piece id group
## 1 61.21082 35.65007 1 FALSE 1 0 0.1
## 2 62.23065 35.27066 2 FALSE 1 0 0.1

ggplot(data = df_for) +
geom_polygon(aes(x = long, y = lat,
group = group),
fill = "#FFFFFF",
color = "#000000")

rnaturalearth의 세계지도

ne_countries() 함수로 반환되는 객체는 SpatialPolygonsDataFrame 객체이기 때문에 이를 데이터프레임으로 변환해주는 ggplot2 패키지의 fortify() 함수로 변환 후 시각화를 하는 것이 정석이다.

대륙별 시각화

별도의 대륙을 시각화 하려면 다음과 같다.

1
2
3
4
5
6
7
8
ne_map = ne_countries(scale = "small", continent = "Asia")
df_for = fortify(ne_map)

ggplot(data = df_for) +
geom_polygon(aes(x = long, y = lat,
group = group),
fill = "#FFFFFF",
color = "#000000")

rnaturalearth의 아시아 대륙 지도

국가별 시각화

별도의 국가를 시각화 하려면 다음과 같다.

1
2
3
4
5
6
7
8
ne_map = ne_countries(scale = "small", country = "South Korea")
df_for = fortify(ne_map)

ggplot(data = df_for) +
geom_polygon(aes(x = long, y = lat,
group = group),
fill = "#FFFFFF",
color = "#000000")

rnaturalearth의 한국 지도

rworldmap

rworldmap 패키지는 rnaturalearth 패키지보다 오래되었고 버전이 높다. 하지만 사실상 데이터의 원 출처는 Natural Earth 이다.

데이터 확인

rworldmap 패키지는 rnaturalearth 패키지에 비해 상대적으로 더 많은 정보를 제공하는데 국가별 상세 정보는 “countriesCoarse” 객체와 “countryExData” 객체에 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
library("rworldmap")
info_1 = countriesCoarse@data
head(info_1, 2)
## ScaleRank LabelRank FeatureCla SOVEREIGNT SOV_A3 ADM0_DIF LEVEL
## 1 1 1 Admin-0 countries Afghanistan AFG 0 2
## 2 1 1 Admin-0 countries Angola AGO 0 2
## TYPE ADMIN ADM0_A3 GEOU_DIF GEOUNIT GU_A3 SU_DIF
## 1 Sovereign country Afghanistan AFG 0 Afghanistan AFG 0
## 2 Sovereign country Angola AGO 0 Angola AGO 0
## SUBUNIT SU_A3 NAME ABBREV POSTAL
## 1 Afghanistan AFG Afghanistan Afg. AF
## 2 Angola AGO Angola Ang. AO
## NAME_FORMA TERR_ NAME_SORT MAP_COLOR POP_EST
## 1 Islamic State of Afghanistan <NA> Afghanistan 7 28400000
## 2 Republic of Angola <NA> Angola 1 12799293
## GDP_MD_EST FIPS_10_ ISO_A2 ISO_A3 ISO_N3 ISO3 LON LAT ISO3.1
## 1 22270 0 AF AFG 4 AFG 66.08669 33.85640 AFG
## 2 110300 0 AO AGO 24 AGO 17.50291 -12.29155 AGO
## ADMIN.1 REGION continent GEO3major GEO3
## 1 Afghanistan Asia Eurasia Asia and the Pacific South Asia
## 2 Angola Africa Africa Africa Southern Africa
## IMAGE24 GLOCAF Stern SRESmajor
## 1 India+ Rest of South Asia Central Asia ASIA
## 2 Southern Africa Sub-Sarahan Africa South+E Africa ALM
## SRES GBD AVOIDnumeric
## 1 South Asia (SAS) Asia, South 21
## 2 Sub-Saharan Africa (AFR) Sub-Saharan Africa, Central 24
## AVOIDname LDC SID LLDC
## 1 Rest of Central Asia LDC other LLDC
## 2 Southern and East Africa LDC other other

info_2 = countryExData
dim(info_2)
## [1] 149 80

“countriesCoarse” 객체의 “data”슬롯의 주요 변수는 다음과 같다.
● REGION: 특정 국가의 소속 대륙명
● NAME: 국가명
● NAME_FORMA: 정식 국가명
● ISO3: 국가 3 CODE(영문 대문자 3개로 표기)
● LON: 국가의 대표 위치의 경도(longitude)
● LAT: 국가의 대표 위치의 위도(latitude)

참고로 대륙명 정보는 “REGION” 뿐만 아니라 “continent”에도 있는데 여기에는 유럽과 아시아를 묶어놓은 “Eurasia”로 지정하고 있어 “REGION” 사용을 권장한다.

세계지도 시각화

“countriesCoarse” 객체를 그대로 fortify() 함수를 활용하여 데이터프레임 변환 후 시각화 하면 세계지도를 확인할 수 있다.

1
2
3
4
5
6
7
8
df_map = fortify(countriesCoarse)
head(df_map)

ggplot(data = df_map,
aes(x = long, y = lat,
group = group)) +
geom_polygon(fill = "#FFFFFF",
color = "#000000")

rworldmap의 세계지도

대륙별 시각화

앞에서 데이터프레임으로 변환한 “df_map” 객체를 활용한다. 보다 정확하고 빠른 처리를 위해 앞에서 생성한 “info_1” 객체에서 특정 대륙명에 해당하는 국가명을 별도로 뽑아 필터링을 하는 것을 추천하며 코드는 다음과 같다.

1
2
3
4
5
6
vec_conti = unique(info_1[info_1$REGION == "Asia", "NAME"])
ggplot(data = df_map[df_map$id %in% vec_conti, ],
aes(x = long, y = lat,
group = group)) +
geom_polygon(fill = "#FFFFFF",
color = "#000000")

rworldmap의 아시아 대륙 지도

국가별 시각화

1
2
3
4
5
ggplot(data = df_map[df_map$id == "South Korea", ],
aes(x = long, y = lat,
group = group)) +
geom_polygon(fill = "#FFFFFF",
color = "#000000")

rworldmap의 한국 지도

<R 지도 핸들링 시리즈>
R) ggplot2 - 세계지도
R) ggplot2 - 한국 행정경계지도
R) ggplot2 - 서울 통계자료 매핑
Etc) GCP - 가입 및 지오코딩(geocoding) API 신청
R) 전처리 - 지오코딩(Google Map)
R) 시각화 - Google 지도
R) 전처리 - 지점간 거리 계산
R) 전처리 - 지리 좌표계(CRS) 변환

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×