Data_Visualization CH7

code
data_visualization
rstudio
Author

Seongtaek

Published

April 13, 2023

HTML파일로 보기

Figure 4.4, Figure 4.6

1 데이터 시각화 실습 : 지역 정보 시각화 Figure 4.4, 4.6

1.1 패키지 불러오기

#install.packages("geojsonsf")
library(geojsonsf)
library(sf)
#> Linking to GEOS 3.9.3, GDAL 3.5.2, PROJ 8.2.1; sf_use_s2() is TRUE
library(ggplot2)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(colorspace)

1.2 데이터 불러오기

  • KOR_SIDO.json : 대한민국 시,도 정보
  • KOR_SIGU.json : 대한민국 시,군,구 정보
  • 202202_주민등록인구및세대현황.csv
KOR_SIDO <- geojson_sf('C:/Users/seong taek/Desktop/3-1 DataVisualize/data_visualize/KOR_SIDO.json')

KOR_SIGU <- geojson_sf('C:/Users/seong taek/Desktop/3-1 DataVisualize/data_visualize/KOR_SIGU.json')

kor_202202 <- read.csv('C:/Users/seong taek/Desktop/3-1 DataVisualize/data_visualize/202202_주민등록인구및세대현황.csv')

1.3 전처리

### 컬럼 클래스(타입) 확인
kor_202202 %>% sapply(class)
#>      행정구역 행정구역_코드      총인구수        세대수   세대당_인구 
#>   "character"     "numeric"     "numeric"     "numeric"     "numeric" 
#>   남자_인구수   여자_인구수     남여_비율 
#>     "numeric"     "numeric"     "numeric"

### `행정구역_코드`를 numeric → character형식으로 변환
kor_202202$행정구역_코드 <- kor_202202$행정구역_코드 %>% format()

use_map <- KOR_SIGU
use_map %>% head()
#> Simple feature collection with 6 features and 3 fields
#> Geometry type: POLYGON
#> Dimension:     XY
#> Bounding box:  xmin: 127.5071 ymin: 37.06363 xmax: 129.1596 ymax: 38.23041
#> Geodetic CRS:  WGS 84
#>   SIG_CD   SIG_ENG_NM SIG_KOR_NM                       geometry
#> 1  42110 Chuncheon-si     춘천시 POLYGON ((127.6047 38.07265...
#> 2  42130     Wonju-si     원주시 POLYGON ((128.1086 37.2988,...
#> 3  42150 Gangneung-si     강릉시 POLYGON ((129.0479 37.64961...
#> 4  42170   Donghae-si     동해시 POLYGON ((129.1596 37.47574...
#> 5  42190   Taebaek-si     태백시 POLYGON ((129.0121 37.31012...
#> 6  42210    Sokcho-si     속초시 POLYGON ((128.6087 38.16128...

### 병합할 컬럼 동일화
use_map$행정구역_코드 <- paste(use_map$SIG_CD, "00000", sep = "")

### 공통된 '행정구역_코드'를 기준으로 병합 
use_map <- use_map %>% merge(kor_202202, by = "행정구역_코드", all.x=T)

1.4 Figure 4.4 - 총 인구수

  • 사용 데이터셋 : use_map
  • fill : 총인구수
  • geom_sf (지리적 객체 그래프)
    • 경계선 색상
  • coord_sf
    • 지도 좌표계 제거
  • scale_fill_distiller
    • 이름 : “인구수”
    • 팔레트 색상 설정
    • 연속형 색상 척도 사용
    • 결측값 색상 설정
    • 색상 척도 방향 설정 : 작은 값 → 큰 값
    • 색상 척도 눈금 설정
    • 색상 척도 라벨 설정, 천 단위 옵션, 지수표기법 미사용
  • 테마 : 미니멀
  • 테마 옵션
    • 범례 제목 위치 지정
    • 범례 텍스트 위치 지정
    • 범례 위치 지정
ggplot(use_map, aes(fill = 총인구수)) +
geom_sf(color = "gray90") +
coord_sf(datum = NA) +
scale_fill_distiller(name = "인구수",
                      palette = "Blues",
                      type = "seq",
                      na.value = "grey60",
                      direction = 1,
                      breaks = seq(0,10,2) * 1e+5,
                      labels = format(seq(0,10,2) * 1e+5,
                                      big.mark = ",", scientific = F),) +
theme_minimal() +
theme(legend.title.align = 0.5,
      legend.text.align = 1.0,
      legend.position = c(.85, .2))

1.5 광주만 뽑기

### filter 이용 광주지역만 추출
use_map %>%
  filter(substr(행정구역_코드,1,2) == "29") %>% 
  ggplot(aes(fill = 총인구수)) +
  geom_sf(color = "gray90") +
  coord_sf(datum = NA) +
  scale_fill_distiller(name = "인구수",
                       palette = "Blues",
                       type = "seq",
                       na.value = "grey60",
                       direction = 1,
                       breaks = seq(0,10,2) * 1e+5,
                       labels = format(seq(0,10,2) * 1e+5,
                                       big.mark = ",", scientific = F),) +
  theme_minimal() +
  theme(legend.title.align = 0.5,
        legend.text.align = 1.0,
        legend.position = c(1, .2))

1.6 Figure 4.6 - 남여 비율

  • 사용 데이터셋 : use_map
  • fill : 남여_비율
  • geom_sf (지리적 객체 그래프)
  • coord_sf
    • 지도 좌표계 제거
  • scale_fill_continuous_diverging
    • 이름 : “남자/여자”
    • 팔레트 색상 설정
    • 색상 척도 : 중앙값 기준
    • 색상 척도 범위 설정
    • 색상 척도 순서 반전
  • 테마 : 미니멀
  • 테마 옵션
    • 범례 제목 위치 지정
    • 범례 텍스트 위치 지정
    • 범례 위치 지정
ggplot(use_map, aes(fill = 남여_비율)) +
geom_sf() +
coord_sf(datum = NA) +
scale_fill_continuous_diverging(name = "남자/여자",
                                palette = "Blue-Red",
                                mid = 1,
                                limits = 1 + c(-1, 1)*0.35,
                                rev = T) +
theme_minimal() +
theme(legend.title.align = 0.5,
      legend.text.align = 1.0,
      legend.position = c(.95, .3))

2 과제

  • 2023년3월 총인구수 - Figure 4.4

2.1 데이터 불러오기

  • 202303_202303_주민등록인구및세대현황_월간.csv
  • KOR_SIGU.json : 대한민국 시,군,구 정보
kor_202303 <- read.csv('C:/Users/seong taek/Desktop/3-1 DataVisualize/data_visualize/202303_202303_주민등록인구및세대현황_월간.csv',fileEncoding = "CP949")
KOR_SIGU <- geojson_sf('C:/Users/seong taek/Desktop/3-1 DataVisualize/data_visualize/KOR_SIGU.json')

kor_202303 %>% head()
#>                         행정구역 X2023년03월_총인구수 X2023년03월_세대수
#> 1       서울특별시  (1100000000)            9,426,404          4,463,385
#> 2 서울특별시 종로구 (1111000000)              141,060             72,679
#> 3   서울특별시 중구 (1114000000)              120,963             63,862
#> 4 서울특별시 용산구 (1117000000)              217,756            109,735
#> 5 서울특별시 성동구 (1120000000)              280,240            133,513
#> 6 서울특별시 광진구 (1121500000)              336,801            169,787
#>   X2023년03월_세대당.인구 X2023년03월_남자.인구수 X2023년03월_여자.인구수
#> 1                    2.11               4,566,299               4,860,105
#> 2                    1.94                  68,170                  72,890
#> 3                    1.89                  58,699                  62,264
#> 4                    1.98                 104,640                 113,116
#> 5                    2.10                 136,233                 144,007
#> 6                    1.98                 162,209                 174,592
#>   X2023년03월_남여.비율
#> 1                  0.94
#> 2                  0.94
#> 3                  0.94
#> 4                  0.93
#> 5                  0.95
#> 6                  0.93

KOR_SIGU %>% head()
#> Simple feature collection with 6 features and 3 fields
#> Geometry type: POLYGON
#> Dimension:     XY
#> Bounding box:  xmin: 127.5071 ymin: 37.06363 xmax: 129.1596 ymax: 38.23041
#> Geodetic CRS:  WGS 84
#>   SIG_CD   SIG_ENG_NM SIG_KOR_NM                       geometry
#> 1  42110 Chuncheon-si     춘천시 POLYGON ((127.6047 38.07265...
#> 2  42130     Wonju-si     원주시 POLYGON ((128.1086 37.2988,...
#> 3  42150 Gangneung-si     강릉시 POLYGON ((129.0479 37.64961...
#> 4  42170   Donghae-si     동해시 POLYGON ((129.1596 37.47574...
#> 5  42190   Taebaek-si     태백시 POLYGON ((129.0121 37.31012...
#> 6  42210    Sokcho-si     속초시 POLYGON ((128.6087 38.16128...

2.2 전처리

#install.packages("stringr")
library(stringr) # 고급 문자 추출 패키지
#> Warning: package 'stringr' was built under R version 4.2.2

### 쉼표없는 총인구수 컬럼 생성
### 행정구역 코드만 추출한 컬럼 생성
kor_202303 <- kor_202303 %>% 
  mutate(총인구수_202303 = gsub(",","", X2023년03월_총인구수),
         행정구역_코드 = str_sub(kor_202303$행정구역, -11, -2))

### 컬럼 클래스(타입) 확인
kor_202303 %>% sapply(class)
#>                행정구역    X2023년03월_총인구수      X2023년03월_세대수 
#>             "character"             "character"             "character" 
#> X2023년03월_세대당.인구 X2023년03월_남자.인구수 X2023년03월_여자.인구수 
#>               "numeric"             "character"             "character" 
#>   X2023년03월_남여.비율         총인구수_202303           행정구역_코드 
#>               "numeric"             "character"             "character"

### '총인구수_202303' 컬럼 character → numeric 변환
kor_202303$총인구수_202303 <- kor_202303$총인구수_202303 %>% as.numeric()

### 병합할 컬럼 동일화
KOR_SIGU_use <- KOR_SIGU
KOR_SIGU_use$행정구역_코드 <- paste(KOR_SIGU_use$SIG_CD, "00000", sep = "")

kor_202303 %>% head()
#>                         행정구역 X2023년03월_총인구수 X2023년03월_세대수
#> 1       서울특별시  (1100000000)            9,426,404          4,463,385
#> 2 서울특별시 종로구 (1111000000)              141,060             72,679
#> 3   서울특별시 중구 (1114000000)              120,963             63,862
#> 4 서울특별시 용산구 (1117000000)              217,756            109,735
#> 5 서울특별시 성동구 (1120000000)              280,240            133,513
#> 6 서울특별시 광진구 (1121500000)              336,801            169,787
#>   X2023년03월_세대당.인구 X2023년03월_남자.인구수 X2023년03월_여자.인구수
#> 1                    2.11               4,566,299               4,860,105
#> 2                    1.94                  68,170                  72,890
#> 3                    1.89                  58,699                  62,264
#> 4                    1.98                 104,640                 113,116
#> 5                    2.10                 136,233                 144,007
#> 6                    1.98                 162,209                 174,592
#>   X2023년03월_남여.비율 총인구수_202303 행정구역_코드
#> 1                  0.94         9426404    1100000000
#> 2                  0.94          141060    1111000000
#> 3                  0.94          120963    1114000000
#> 4                  0.93          217756    1117000000
#> 5                  0.95          280240    1120000000
#> 6                  0.93          336801    1121500000
KOR_SIGU_use %>% head()
#> Simple feature collection with 6 features and 4 fields
#> Geometry type: POLYGON
#> Dimension:     XY
#> Bounding box:  xmin: 127.5071 ymin: 37.06363 xmax: 129.1596 ymax: 38.23041
#> Geodetic CRS:  WGS 84
#>   SIG_CD   SIG_ENG_NM SIG_KOR_NM                       geometry 행정구역_코드
#> 1  42110 Chuncheon-si     춘천시 POLYGON ((127.6047 38.07265...    4211000000
#> 2  42130     Wonju-si     원주시 POLYGON ((128.1086 37.2988,...    4213000000
#> 3  42150 Gangneung-si     강릉시 POLYGON ((129.0479 37.64961...    4215000000
#> 4  42170   Donghae-si     동해시 POLYGON ((129.1596 37.47574...    4217000000
#> 5  42190   Taebaek-si     태백시 POLYGON ((129.0121 37.31012...    4219000000
#> 6  42210    Sokcho-si     속초시 POLYGON ((128.6087 38.16128...    4221000000

### 공통된 '행정구역_코드'를 기준으로 병합 
KOR_SIGU_use <- KOR_SIGU_use %>% merge(kor_202303, by = "행정구역_코드", all.x=T)
KOR_SIGU_use %>% head()
#> Simple feature collection with 6 features and 12 fields
#> Geometry type: POLYGON
#> Dimension:     XY
#> Bounding box:  xmin: 126.9446 ymin: 37.50654 xmax: 127.1153 ymax: 37.6317
#> Geodetic CRS:  WGS 84
#>   행정구역_코드 SIG_CD    SIG_ENG_NM SIG_KOR_NM
#> 1    1111000000  11110     Jongno-gu     종로구
#> 2    1114000000  11140       Jung-gu       중구
#> 3    1117000000  11170    Yongsan-gu     용산구
#> 4    1120000000  11200  Seongdong-gu     성동구
#> 5    1121500000  11215   Gwangjin-gu     광진구
#> 6    1123000000  11230 Dongdaemun-gu   동대문구
#>                           행정구역 X2023년03월_총인구수 X2023년03월_세대수
#> 1   서울특별시 종로구 (1111000000)              141,060             72,679
#> 2     서울특별시 중구 (1114000000)              120,963             63,862
#> 3   서울특별시 용산구 (1117000000)              217,756            109,735
#> 4   서울특별시 성동구 (1120000000)              280,240            133,513
#> 5   서울특별시 광진구 (1121500000)              336,801            169,787
#> 6 서울특별시 동대문구 (1123000000)              337,574            171,140
#>   X2023년03월_세대당.인구 X2023년03월_남자.인구수 X2023년03월_여자.인구수
#> 1                    1.94                  68,170                  72,890
#> 2                    1.89                  58,699                  62,264
#> 3                    1.98                 104,640                 113,116
#> 4                    2.10                 136,233                 144,007
#> 5                    1.98                 162,209                 174,592
#> 6                    1.97                 165,933                 171,641
#>   X2023년03월_남여.비율 총인구수_202303                       geometry
#> 1                  0.94          141060 POLYGON ((127.0118 37.58157...
#> 2                  0.94          120963 POLYGON ((127.0234 37.57191...
#> 3                  0.93          217756 POLYGON ((127.009 37.54413,...
#> 4                  0.95          280240 POLYGON ((127.0724 37.55996...
#> 5                  0.93          336801 POLYGON ((127.1153 37.55676...
#> 6                  0.97          337574 POLYGON ((127.0711 37.60732...

2.3 Figure 4.4 - 2023년3월 총인구수

  • 사용 데이터셋 : KOR_SIGU_use
  • fill : 총인구수_202303
  • geom_sf (지리적 객체 그래프)
    • 경계선 색상
  • coord_sf
    • 지도 좌표계 제거
  • scale_fill_distiller
    • 이름 : “2023년 3월 총인구수”
    • 팔레트 색상 설정
    • 연속형 색상 척도 사용
    • 결측값 색상 설정
    • 색상 척도 방향 설정 : 작은 값 → 큰 값
    • 색상 척도 눈금 설정
    • 색상 척도 라벨 설정, 천 단위 옵션, 지수표기법 미사용
  • 테마 : 미니멀
  • 테마 옵션
    • 범례 제목 위치 지정
    • 범례 텍스트 위치 지정
    • 범례 위치 지정
ggplot(KOR_SIGU_use, aes(fill = 총인구수_202303)) +
geom_sf(color = "gray90") +
coord_sf(datum = NA) +
scale_fill_distiller(name = "2023년 3월 총인구수",
                      palette = "Blues",
                      type = "seq",
                      na.value = "grey60",
                      direction = 1,
                      breaks = seq(0,10,2) * 1e+5,
                      labels = format(seq(0,10,2) * 1e+5,
                                      big.mark = ",", scientific = F),) +
theme_minimal() +
theme(legend.title.align = 0.5,
      legend.text.align = 1.0,
      legend.position = c(.85, .2))