ch05 - Log Scale Visualisation

Page content

공지

  • 본 포스트를 읽고 가급적 전체 내용 숙지를 위해 구매하는 것을 권유한다.

개요

  • 수치형 자료를 Y축으로 놓는 그래프는 언제나 힘들었다.
  • log Scale을 통해 값의 크기를 줄이기는 하지만, Y축을 어떻게 표현하는 것이 좋을지에 대한 고민은 늘 있어왔다.
  • 시각화 이론 중심의 포스팅이기에 코드 리뷰 및 해석은 생략한다.

문제점

  • log Scale을 적용했을 때와 그렇지 않을 때의 그래프를 비교해본다.

(1) 패키지 불러오기

  • 각각의 패키지를 불러온다.
  • 이 때, 데이터는 dviz.supp 저자인 Claus O. WilkeGithub Repo에서 가져와야 한다.
    • 경고: 이 부분이 초급자 분들에게는 쉽지가 않다.
  • 우선, 사전에 설치해야 할 패키지가 존재한다.
  • 현재 필자 개발환경 Spec은 다음과 같다.
> sessionInfo()
R version 4.0.2 (2020-06-22)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Catalina 10.15.6
  • 아래는 추가적으로 설치한 파일이다.
install.packages("devtools")

devtools::install_github("wilkelab/cowplot")
library(cowplot)

install.packages("colorspace")
library(colorspace)

devtools::install_github("clauswilke/colorblindr")
library(colorblindr)

devtools::install_github("clauswilke/dviz.supp")
library(dviz.supp)
  • 위 패키지들을 설치하는데 꽤 시간이 걸렸다.
library(lubridate) # 날짜 관련 패키지
library(forcats)   # 시계열 관련 패키지
library(tidyr)     # 데이터 핸들링 패키지
library(ggrepel)   # 시각화 관련 패키지
library(dviz.supp) # 저자의 개인 Repo 패키지: 교재 있는 데이터 활용 및 그래프를 구현하려면 필수적으로 설치 되어야 함.
library(kableExtra) # 데이터 출력 Table을 HTML로 변환하기 위한 패키지 

(2) 데이터 확인

  • 데이터는 US_Census 데이터를 기반으로 한다.
    • 자료 출처: 2010년도 미국 10개년 인구조사
  • 주의: 한글 폰트는 일단 생략했다.

소스코드 참���: https://github.com/clauswilke/dataviz/blob/master/coordinate_systems_axes.Rmd

set.seed(3878)

US_census %>% filter(state == "Texas") %>%
  select(name, pop2010) %>%
  extract(name, "county", regex = "(.+) County") %>%
  mutate(popratio = pop2010/median(pop2010)) %>%
  arrange(desc(popratio)) %>%
  mutate(index = 1:n(),
         label = ifelse(index <= 3 | index > n()-3 | runif(n()) < .04, county, ""),
         label_large = ifelse(index <= 6, county, "")) -> tx_counties

kable(tx_counties) %>%
  kable_styling(bootstrap_options = c("striped", "hover")) %>% 
  scroll_box(width = "500px", height = "200px")
countypop2010popratioindexlabellabel_large
Harris4092459222.64615641HarrisHarris
Dallas2368139128.83624392DallasDallas
Tarrant180903498.41869323TarrantTarrant
Bexar171477393.29051744Bexar
Travis102426655.72417175Travis
El Paso80064743.55840276El Paso
Collin78234142.56248307
Hidalgo77476942.15053598
Denton66261436.04885489
Fort Bend58537531.846743910
Montgomery45574624.794407311
Williamson42267922.995430112
Cameron40622022.099994613
Nueces34022318.509493514
Brazoria31316617.037484415
Bell31023516.878026216
Galveston29130915.848376017Galveston
Lubbock27883115.169522918Lubbock
Jefferson25227313.724661319
Webb25030413.617539920
McLennan23490612.779827021
Smith20971411.409281322
Brazos19485110.600674623
Hays1571078.547249924
Johnson1509348.211414025
Ellis1496108.139383126
Ector1371307.460421127
Midland1368727.446384928
Guadalupe1315337.155921929
Taylor1315067.154453030
Wichita1315007.154126531
Gregg1217306.622599432
Potter1210736.586856033
Grayson1208776.576192834
Randall1207256.567923435
Parker1169276.361297036
Tom Green1102245.996627037
Comal1084725.901311138Comal
Kaufman1033505.622653839
Bowie925655.035906640Bowie
Victoria867934.721886741
Angelina867714.720689842
Hunt861294.685762543
Orange818374.452260544
Henderson785324.272455345
Rockwall783374.261846546
Liberty756434.115282147
Coryell753884.101409148
Bastrop741714.035199449
Walker678613.691910150
Harrison656313.570589251
San Patricio648043.525597152
Nacogdoches645243.510364053
Starr609683.316903354
Wise591273.216745655
Anderson584583.180349356
Hardin546352.972362857
Maverick542582.951852558
Rusk533302.901365559
Van Zandt525792.860508160
Hood511822.784505761
Cherokee508452.766171662
Lamar497932.708938663
Kerr496252.699798764
Val Verde488792.659213365
Navarro477352.596975166
Medina460062.502910667
Polk454132.470649068
Atascosa449112.443338269
Waller432052.350525070Waller
Wilson429182.334911071
Burnet427502.325771272
Wood419642.283009673
Wharton412802.245797374
Jim Wells408382.221750775
Upshur393092.138567076
Cooke384372.091126777
Brown381062.073119078
Caldwell380662.070942879
Erath378902.061367780
Matagorda367021.996735881
Hale362731.973396482
Jasper357101.942767083
Hopkins351611.912899284
Chambers350961.909362985
Hill350891.908982186
Howard350121.904793087
Fannin339151.845111888
Washington337181.834394289
Kendall334101.817637890
Titus323341.759099191
Kleberg320611.744246892
Bee318611.733366093
Cass304641.657363694
Austin284171.545998695
Palo Pinto281111.529351096
Grimes266041.447364197
Uvalde264051.436537798
San Jacinto263841.435395299San Jacinto
Shelby254481.3844731100
Gillespie248371.3512323101
Milam247571.3468799102
Fayette245541.3358359103
Panola237961.2945977104
Houston237321.2911158105
Limestone233841.2721832106
Aransas231581.2598879107
Hockley229351.2477558108
Gray225351.2259942109
Hutchinson221501.2050487110
Willacy221341.2041782111
Moore219041.1916653112
Tyler217661.1841576113
Calhoun213811.1632120114
Colorado208741.1356292115
Bandera204851.1144660116
Jones202021.0990697117
DeWitt200971.0933573118
Freestone198161.0780697119
Gonzales198071.0775801120
Montague197191.0727926121
Lampasas196771.0705076122
Deaf Smith193721.0539144123
Llano193011.0500517124
Lavaca192631.0479843125
Eastland185831.0109896126
Young185501.0091943127
Bosque182120.9908057128
Falls178660.9719819129
Gaines175260.9534846130
Frio172170.9366737131
Burleson171870.9350416132
Scurry169210.9205702133
Leon168010.9140417134
Robertson166220.9043034135
Lee166120.9037593136
Pecos155070.8436429137
Nolan152160.8278113138
Karnes148240.8064850139
Andrews147860.8044176140
Trinity145850.7934824141
Newton144450.7858658142
Jackson140750.7657364143
Zapata140180.7626353144
Lamb139770.7604048145
Comanche139740.7602416146
Dawson138330.7525706147
Reeves137830.7498504148
Madison136640.7433763149
Callahan135440.7368478150
Wilbarger135350.7363582151
Morris129340.7036614152
Red River128600.6996355153
Terry126510.6882651154
Camp124010.6746641155
Duval117820.6409880156
Zavala116770.6352756157
Live Oak115310.6273326158
Rains109140.5937653159
Sabine108340.5894130160
Clay107520.5849519161
Ward106580.5798379162
Franklin106050.5769545163
Marion105460.5737446164
Runnels105010.5712964165
Blanco104970.5710788166
Parmer102690.5586747167
Ochiltree102230.5561721168
Dimmit99960.5438224169
Stephens96300.5239106170
Mitchell94030.5115609171Mitchell
Brewster92320.5022578172
Archer90540.4925739173
Jack90440.4920298174
Coleman88950.4839236175
San Augustine88650.4822915176
Hamilton85170.4633589177
Somervell84900.4618900178
McCulloch82830.4506284179
Castro80620.4386051180
Yoakum78790.4286491181
Swisher78540.4272890182
Presidio78180.4253305183
Refugio73830.4016648184
Brooks72230.3929601185
Goliad72100.3922529186Goliad
Bailey71650.3898047187
Winkler71100.3868125188
Childress70410.3830586189
La Salle68860.3746260190
Dallam67030.3646700191
Garza64610.3515043192
Floyd64460.3506882193
Carson61820.3363256194
San Saba61310.3335509195
Hartley60620.3297971196
Crosby60590.3296339197
Lynn59150.3217997198
Haskell58990.3209292199
Hansford56130.3053697200
Wheeler54100.2943257201
Jim Hogg53000.2883412202
Delta52310.2845873203
Mills49360.2685382204
Martin47990.2610848205
Kimble46070.2506392206
Crane43750.2380175207
Hardeman41390.2251782208
Sutton41280.2245797209
Concho40870.2223492210
Mason40120.2182689211
Fisher39740.2162015212
Hemphill38070.2071160213
Baylor37260.2027093214
Crockett37190.2023285215
Knox37190.2023285216
Donley36770.2000435217
Kinney35980.1957456218
Hudspeth34760.1891083219
Schleicher34610.1882923220
Shackelford33780.1837767221
Reagan33670.1831783222
Upton33550.1825254223
Hall33530.1824166224
Coke33200.1806213225
Real33090.1800228226Real
Lipscomb33020.1796420227Lipscomb
Cochran31270.1701213228
Collingsworth30570.1663130229
Sherman30340.1650617230
Dickens24440.1329634231
Culberson23980.1304608232
Jeff Davis23420.1274142233
Menard22420.1219738234
Oldham20520.1116370235
Edwards20020.1089168236
Armstrong19010.1034220237
Throckmorton16410.0892770238
Briscoe16370.0890594239
Irion15990.0869920240
Cottle15050.0818780241
Stonewall14900.0810620242
Foard13360.0726837243
Glasscock12260.0666993244
Motley12100.0658288245
Sterling11430.0621838246
Terrell9840.0535335247
Roberts9290.0505413248
Kent8080.0439584249
McMullen7070.0384636250
Borden6410.0348730251
Kenedy4160.0226321252Kenedy
King2860.0155595253King
Loving820.0044611254Loving

(3) 모호한 시각화

  • 주어진 데이터를 가지고 시각화를 작성한다.
temp_font <- "Times New Roman"

counties_lin <- ggplot(tx_counties, aes(x = index, y = popratio)) +
  geom_point(size = 0.5, color = "#0072B2") +
  geom_text_repel(aes(label = label_large), point.padding = .4, color = "black",
                  min.segment.length = 0, family = temp_font) +
  scale_y_continuous(name = "population number / median") +
  scale_x_continuous(limits = c(.5, nrow(tx_counties) + .5), expand = c(0, 0),
                     breaks = NULL, #c(1, 50*(1:5)),
                     name = "Texas counties, from most to least populous") +
  theme_dviz_hgrid(font_family = temp_font) +
  theme(axis.line = element_blank(),
        plot.margin = margin(3, 7, 3, 1.5)) 

ggdraw(counties_lin, clip = "on") + 
  draw_text(paste0("bad", "  "), x=1, y=1, vjust=1.1, hjust=1, size=14, angle = 0,
              color="#d02138", alpha=1, family = temp_font, fontface = "plain") +
  draw_line(c(1, 1), c(0, 1), size=2.8, color="#d02138", alpha=1)

  • 위 그래프는 전형적인 선형 스케일을 옮겨 담은 것이다.
    • 선형(linear)스케일은 대개 데이터를 정확하게 보여주기도 하지만, 독자��게 보다 강한 메시지를 주기 위해서는 비선형 스케일이 더 좋을 때가 있다.
    • 위 데이터에서 인구 수가 중간값이 카운티와 중간 값에 훨씬 못 미치는 카운티 사이의 인구 차이가 잘 드러나지 않으면, 전달력이 그만큼 떨어진다는 얘기다.

로그 스케일 적용

  • 로그 변환을 적용한 그래프를 작성한다.
  • 그래프를 먼저 본 후, 추가적인 이론 설명을 진행한다.

(1) 보정된 시각화

  • 시각화 코드는 아래와 같다.
ggplot(tx_counties, aes(x = index, y = popratio)) +
  geom_hline(yintercept = 1, linetype = 2, color = "grey40") +
  geom_point(size = 0.5, color = "#0072B2") +
  geom_text_repel(aes(label = label), point.padding = .4, color = "black",
                  min.segment.length = 0, family = temp_font) +
  scale_y_log10(breaks = c(.01, .1, 1, 10, 100),
                name = "population number / median",
                labels = label_log10) +
  scale_x_continuous(limits = c(.5, nrow(tx_counties) + .5), expand = c(0, 0),
                     breaks = NULL, #c(1, 50*(1:5)),
                     name = "Texas counties, from most to least populous") +
  theme_dviz_hgrid(font_family = temp_font) +
  theme(axis.line = element_blank(),
        plot.margin = margin(3, 7, 3, 1.5))

(2) 그래프 해석

  • 위 그래프는 비율 값을 로그 스케일로 사용할 때의 예시이다. - 텍사스의 카운티별 인구를 텍사스 전체 인구의 중간 값으로 나눈다고 생각할 때, 이 계산으로 얻은 비율 값은 1보다 크거나 작다.
    • 다시 말하면, 비율 값이 정확하게 1이면 그 카운티는 텍사즈 주 전체의 중간 값과 똑같다고 볼 수 있다.
  • 대칭 형태의 그래프를 보여주면서, 인구가 많은 지역과 그렇지 못한 지역의 편차를 보여주는 매우 훌륭한 그래프가 완성 되었다.
  • 지역별로 편차가 심하게 큰 데이터에는 로그스케일 변환 그래프가 유용할 수 있다.
  • 해리스의 카운티는 4,092,459명이지만, 가장 적은 카운티는 82명일 수도 있다.
  • 이러한 경우에 로그 스케일은 매우 적정할 수 있다.

(3) 제곱근 스케일

  • 만약 특정지역의 인구수가 0명으로 기록되었다면 어떻게 할까?
  • 0은 로그 스케일에 표시할 수 없기 때문에, 이럴 경우 제곱근 스케일을 사용한다.
  • 그러나, 다루기가 쉽지 않다.
    • 이 부분은 교재 또는 추후에 별도로 포스팅 하는 것으로 남겨둔다.

소결론

  • 시각화를 그릴 때, 표준점수로 환산해서 그래프를 작성한 적은 몇번 있다.
    • 막대 그래프를 사용했지만, 거리감까지 드는 그래프는 아니었다.
    • 위 그래프는 line + point의 조합으로 나타냈다는 데 의의가 있다.
  • 선형 스케일, 로그 스케일, 그리고 제곱근 스케일의 차이점이 있음을 알게 되었다.

자세한 건 교재를 구��하자.

V. Reference (원서)

Wilke, C. (2019). Fundamentals of Data Visualization. Retrieved July 28, 2020, from https://serialmentor.com/dataviz/

R 강의 소개