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)
![]() |
Figure 4.2, Figure 4.8
1 데이터 시각화 실습 : 막대그래프 Figure 4.2, Figure 4.8
1.1 패키지 불러오기
1.2 RColorBrewer의 모든 컬러 맵 보기
# install.packages("RColorBrewer")
::display.brewer.all() RColorBrewer
1.3 데이터 불러오기, 파악
- US_cescus.csv (미국 인구조사 데이터셋)
- US_regions.csv (미국 지역 분류 정보 데이터셋)
<- read.csv('C:/Users/seong taek/Desktop/3-1 DataVisualize/data_visualize/US_census.csv')
US_census <- read.csv('C:/Users/seong taek/Desktop/3-1 DataVisualize/data_visualize/US_regions.csv')
US_regions
### 차원 파악
%>% dim()
US_census #> [1] 3143 53
%>% dim()
US_regions #> [1] 51 4
### 앞부분 훑어보기
%>% head(2)
US_census #> state name FIPS pop2010 pop2000 age_under_5 age_under_18
#> 1 Alabama Autauga County 1001 54571 43671 6.6 26.8
#> 2 Alabama Baldwin County 1003 182265 140415 6.1 23.0
#> age_over_65 female white black native asian pac_isl two_plus_races hispanic
#> 1 12.0 51.3 78.5 17.7 0.4 0.9 NA 1.6 2.4
#> 2 16.8 51.1 85.7 9.4 0.7 0.7 NA 1.5 4.4
#> white_not_hispanic no_move_in_one_plus_year foreign_born
#> 1 77.2 86.3 2.0
#> 2 83.5 83.0 3.6
#> foreign_spoken_at_home hs_grad bachelors veterans mean_work_travel
#> 1 3.7 85.3 21.7 5817 25.1
#> 2 5.5 87.6 26.8 20396 25.8
#> housing_units home_ownership housing_multi_unit median_val_owner_occupied
#> 1 22135 77.5 7.2 133900
#> 2 104061 76.7 22.6 177200
#> households persons_per_household per_capita_income median_household_income
#> 1 19718 2.7 24568 53255
#> 2 69476 2.5 26469 50147
#> poverty private_nonfarm_establishments private_nonfarm_employment
#> 1 10.6 877 10628
#> 2 12.2 4812 52233
#> percent_change_private_nonfarm_employment nonemployment_establishments firms
#> 1 16.6 2971 4067
#> 2 17.4 14175 19035
#> black_owned_firms native_owned_firms asian_owned_firms pac_isl_owned_firms
#> 1 15.2 NA 1.3 NA
#> 2 2.7 0.4 1.0 NA
#> hispanic_owned_firms women_owned_firms manufacturer_shipments_2007
#> 1 0.7 31.7 NA
#> 2 1.3 27.3 1410273
#> mercent_whole_sales_2007 sales sales_per_capita accommodation_food_service
#> 1 NA 598175 12003 88157
#> 2 NA 2966489 17166 436955
#> building_permits fed_spending area density
#> 1 191 331142 594.44 91.8
#> 2 696 1119082 1589.78 114.6
%>% head()
US_regions #> state state_abr region division
#> 1 Alabama AL South East South Central
#> 2 Alaska AK West Pacific
#> 3 Arizona AZ West Mountain
#> 4 Arkansas AR South West South Central
#> 5 California CA West Pacific
#> 6 Colorado CO West Mountain
1.4 전처리
<- US_census %>%
popgrowth_df left_join(US_regions) %>% # US_census 기준으로 left_join
group_by(region, division, state) %>% # 그룹화할 컬럼 선택
summarise(pop2000 = sum(pop2000, na.rm = T), # 그룹화된 컬럼들의 집계값 설정
pop2010 = sum(pop2010, na.rm = T),
popgrowth = (pop2010 - pop2000)/pop2000,
area = sum(area)) %>%
arrange(popgrowth) %>% # 해당 컬럼 기준으로 오름차순 정렬
ungroup() %>% # 그룹화 해제
mutate(state = factor(state, levels=state), # 팩터로 변환, level 지정
region = factor(region, levels=c('West','South','Midwest','Northeast')))
#> Joining with `by = join_by(state)`
#> `summarise()` has grouped output by 'region', 'division'. You can override
#> using the `.groups` argument.
popgrowth_df#> # A tibble: 51 × 7
#> region division state pop2000 pop2010 popgrowth area
#> <fct> <chr> <fct> <int> <int> <dbl> <dbl>
#> 1 Midwest East North Central Michigan 9938444 9883640 -0.00551 56539.
#> 2 Northeast New England Rhode Island 1048319 1052567 0.00405 1034.
#> 3 South West South Central Louisiana 4468976 4533372 0.0144 43204.
#> 4 Midwest East North Central Ohio 11353140 11536504 0.0162 40861.
#> 5 Northeast Middle Atlantic New York 18976457 19378102 0.0212 47126.
#> 6 South South Atlantic West Virginia 1808344 1852994 0.0247 24038.
#> 7 Northeast New England Vermont 608827 625741 0.0278 9217.
#> 8 Northeast New England Massachusetts 6349097 6547629 0.0313 7800.
#> 9 Midwest East North Central Illinois 12419293 12830632 0.0331 55519.
#> 10 Northeast Middle Atlantic Pennsylvania 12281054 12702379 0.0343 44743.
#> # … with 41 more rows
### 4개 지방의 색 지정
<- c('#E69F00','#56B4E9','#009E73','#F0E442')
region_colors
region_colors#> [1] "#E69F00" "#56B4E9" "#009E73" "#F0E442"
1.5 Figure 4.2
- 사용 데이터셋 : popgrowth_df
- x=state, y=100*popgrowth
- fill : region별
- geom_col (막대 그래프)
- scale_y_continuous
- 이름 : ‘population growth, 2000 to 2010’
- 범위 : 0 ~ 0 : 더욱 직관적인 그래프 표현 가능
- 라벨 : 백분율 형식
- scale_fill_manual
- fill 옵션 색상 : region_colors
- coord_flip() : x축, y축 체인지 → 세로방향 긴 막대를 가로방향으로 짧게 표시
- 테마 : 밝게
- 테마 옵션
- 그래프 패널의 테두리 제거
- y축 그리드 제거
- y축 레이블 제거
- y축 눈금선 제거
- y축 폰트 크기 설정
- 그래프상의 범례 위치 조정
- 범례 배경 색상 설정
ggplot(popgrowth_df, aes(x=state, y=100*popgrowth, fill=region)) +
geom_col() +
scale_y_continuous(name = 'population growth, 2000 to 2010',
labels = scales::percent_format(scale=1),
expand = c(0,0)) +
scale_fill_manual(values = region_colors) +
coord_flip() +
theme_light() +
theme(panel.border = element_blank(),
panel.grid.major.y = element_blank(),
axis.title.y = element_blank(),
axis.ticks.length = unit(0, 'pt'),
axis.text.y = element_text(size = 6),
legend.position = c(.7, .68),
legend.background = element_rect(fill = '#ffffffb0'))
2 예제
- 주민등록 인구 및 세대현황 Figure 4.2
2.1 데이터 불러오기, 파악
- 202202_주민등록인구및세대현황.csv
<- read.csv('C:/Users/seong taek/Desktop/3-1 DataVisualize/data_visualize/202202_주민등록인구및세대현황.csv')
kor_202202
### 앞부분 훑어보기
%>% head()
kor_202202 #> 행정구역 행정구역_코드 총인구수 세대수 세대당_인구 남자_인구수
#> 1 서울특별시 1100000000 9508451 4442586 2.14 4615823
#> 2 서울특별시 종로구 1111000000 144575 73763 1.96 70092
#> 3 서울특별시 중구 1114000000 122167 63644 1.92 59446
#> 4 서울특별시 용산구 1117000000 222413 111134 2.00 106881
#> 5 서울특별시 성동구 1120000000 285137 134286 2.12 138866
#> 6 서울특별시 광진구 1121500000 340494 168975 2.02 164226
#> 여자_인구수 남여_비율
#> 1 4892628 0.94
#> 2 74483 0.94
#> 3 62721 0.95
#> 4 115532 0.93
#> 5 146271 0.95
#> 6 176268 0.93
### 차원 파악
%>% dim()
kor_202202 #> [1] 291 8
### 컬럼 클래스(타입) 확인
%>% sapply(class)
kor_202202 #> 행정구역 행정구역_코드 총인구수 세대수 세대당_인구
#> "character" "numeric" "numeric" "numeric" "numeric"
#> 남자_인구수 여자_인구수 남여_비율
#> "numeric" "numeric" "numeric"
### `행정구역_코드`를 numeric → character형식으로 변환
$행정구역_코드 <- kor_202202$행정구역_코드 %>% format() kor_202202
2.2 전처리
# 행정구역 컬럼의 1,2번째 자리의 값을 지정해서 추출
# 행정구역_코드 컬럼의 3,4번째 자리의 값이 0이 아닌것만 추출
# 해당 열만 선택
# 해당 열 기준으로 오름차순 정렬
<- kor_202202 %>%
kor_202202_use filter(substr(행정구역,1,2) %in% c('서울','대전','대구','부산')) %>%
filter(substr(행정구역_코드,3,4) != '00') %>%
select(행정구역, 총인구수) %>%
arrange(총인구수)
%>% head()
kor_202202_use #> 행정구역 총인구수
#> 1 부산광역시 중구 40582
#> 2 대구광역시 중구 74710
#> 3 부산광역시 동구 88245
#> 4 부산광역시 서구 104618
#> 5 부산광역시 영도구 109991
#> 6 서울특별시 중구 122167
### '시도' 컬럼 생성
$시도 <- sapply(kor_202202_use$행정구역,
kor_202202_usefunction(x) strsplit(x, " ")[[1]][1])
%>% head()
kor_202202_use #> 행정구역 총인구수 시도
#> 1 부산광역시 중구 40582 부산광역시
#> 2 대구광역시 중구 74710 대구광역시
#> 3 부산광역시 동구 88245 부산광역시
#> 4 부산광역시 서구 104618 부산광역시
#> 5 부산광역시 영도구 109991 부산광역시
#> 6 서울특별시 중구 122167 서울특별시
%>% sapply(class)
kor_202202_use #> 행정구역 총인구수 시도
#> "character" "numeric" "character"
# factor 변환, level 지정
$시도 <- factor(kor_202202_use$시도,
kor_202202_uselevels = c("서울특별시",
"대전광역시",
"대구광역시",
"부산광역시"))
$시도 %>% head()
kor_202202_use#> [1] 부산광역시 대구광역시 부산광역시 부산광역시 부산광역시 서울특별시
#> Levels: 서울특별시 대전광역시 대구광역시 부산광역시
$시도 %>% summary()
kor_202202_use#> 서울특별시 대전광역시 대구광역시 부산광역시
#> 25 5 8 16
### 4개 지방의 색 지정
<- RColorBrewer::brewer.pal(4, "Set2") region_colors
2.3 Figure 4.2
- 사용 데이터셋 : kor_202202_use
- x=reorder(행정구역, 총인구수) : ‘총인구수’ 기준으로 ‘행정구역’ 정렬, y=총인구수
- fill : 시도별
- geom_col (막대 그래프)
- scale_y_continuous
- 이름 : ‘총인구수, 2022년 2월’
- 범위 : 0 ~ 0 : 더욱 직관적인 그래프 표현 가능
- 라벨 : 천 단위 구분 기호 사용
- scale_fill_manual
- fill 옵션 색상 : region_colors
- coord_flip() : x축, y축 체인지 → 세로방향 긴 막대를 가로방향으로 짧게 표시
- 테마 : 밝게
- 테마 옵션
- 그래프 패널의 테두리 제거
- y축 그리드 제거
- y축 레이블 제거
- y축 눈금선 제거
- y축 폰트 크기 설정
- 그래프상의 범례 위치 조정
- 범례 배경 색상 설정
ggplot(kor_202202_use, aes(x=reorder(행정구역, 총인구수), y=총인구수, fill=시도)) +
geom_col() +
scale_y_continuous(name = '총인구수, 2022년 2월',
labels = scales::comma,
expand = c(0,0)) +
scale_fill_manual(values = region_colors) +
coord_flip() +
theme_light() +
theme(panel.border = element_blank(),
panel.grid.major.y = element_blank(),
axis.title.y = element_blank(),
axis.ticks.length = unit(0, 'pt'),
axis.text.y = element_text(size = 5),
legend.position = c(.78, .28),
legend.background = element_rect(fill = '#ffffffb0'))
3 Figure 4.8
3.1 전처리
### 4개 지방의 색 지정 + 밝기조정 + 채도조정
<- c('#E69F00','#56B4E9','#009E73','#F0E442') %>% lighten(0.4) %>% desaturate(0.8)
region_colors
region_colors#> [1] "#D9CBBE" "#C3CDD6" "#AABCB3" "#F0EDD6"
### 컬럼 추가 (region_highlight - NA)
<- popgrowth_df %>%
popgrowth_df mutate(region_highlight = ifelse(state %in% c('Texas', 'Louisiana'),
NA, region %>% paste()))
%>% head()
popgrowth_df #> # A tibble: 6 × 8
#> region division state pop2000 pop2010 popgro…¹ area regio…²
#> <fct> <chr> <fct> <int> <int> <dbl> <dbl> <chr>
#> 1 Midwest East North Central Michigan 9.94e6 9.88e6 -0.00551 56539. Midwest
#> 2 Northeast New England Rhode Is… 1.05e6 1.05e6 0.00405 1034. Northe…
#> 3 South West South Central Louisiana 4.47e6 4.53e6 0.0144 43204. <NA>
#> 4 Midwest East North Central Ohio 1.14e7 1.15e7 0.0162 40861. Midwest
#> 5 Northeast Middle Atlantic New York 1.90e7 1.94e7 0.0212 47126. Northe…
#> 6 South South Atlantic West Vir… 1.81e6 1.85e6 0.0247 24038. South
#> # … with abbreviated variable names ¹popgrowth, ²region_highlight
3.2 Figure 4.8
- 사용 데이터셋 : popgrowth_df
- x=state, y=100*popgrowth
- fill : region_highlight별
- geom_col (막대 그래프)
- scale_y_continuous
- 이름 : ‘population growth, 2000 to 2010’
- 범위 : 0 ~ 0 : 더욱 직관적인 그래프 표현 가능
- 라벨 : 백분율 형식
- scale_fill_manual
- fill 옵션 색상 : region_colors
- 그래프상 범례 레이블 지정
- NA 값일 때 색상 지정
- coord_flip() : x축, y축 체인지 → 세로방향 긴 막대를 가로방향으로 짧게 표시
- 테마 : 밝게
- 테마 옵션
- 그래프 패널의 테두리 제거
- y축 그리드 제거
- y축 레이블 제거
- y축 눈금선 제거
- y축 폰트 크기 설정
- 그래프상의 범례 위치 조정
- 범례 배경 색상 설정
ggplot(popgrowth_df, aes(x=state, y=100*popgrowth, fill=region_highlight)) +
geom_col() +
scale_y_continuous(name = 'population growth, 2000 to 2010',
labels = scales::percent_format(scale=1),
expand = c(0,0)) +
scale_fill_manual(values = region_colors,
breaks = c("West", "South", "Midwest", "Northeast"),
na.value = "#56B4E9" %>% darken(0.3)) +
coord_flip() +
theme_light() +
theme(panel.border = element_blank(),
panel.grid.major.y = element_blank(),
axis.title.y = element_blank(),
axis.ticks.length = unit(0, 'pt'),
axis.text.y = element_text(size = 5),
legend.position = c(.58, .58),
legend.background = element_rect(fill = '#ffffffb0')) # color =테두리색
4 예제2
-대전광역시 강조하기 Figure 4.8
### 컬러 지정시 대전 따로 지정
<- c('#E69F00','#56B4E9','#009E73','#F0E442') %>% lighten(0.4) %>% desaturate(0.8)
region_colors
2] <- "#56B4E9" %>% darken(0.3)
region_colors[
region_colors #> [1] "#D9CBBE" "#077DAA" "#AABCB3" "#F0EDD6"
ggplot(kor_202202_use, aes(x=reorder(행정구역, 총인구수), y=총인구수, fill=시도)) +
geom_col() +
scale_y_continuous(name = '총인구수, 2022년 2월',
labels = scales::comma,
expand = c(0,0)) +
scale_fill_manual(values = region_colors) +
coord_flip() +
theme_light() +
theme(panel.border = element_blank(),
panel.grid.major.y = element_blank(),
axis.title.y = element_blank(),
axis.ticks.length = unit(0, 'pt'),
axis.text.y = element_text(size = 5),
legend.position = c(.78, .28),
legend.background = element_rect(fill = '#ffffffb0'))