Data Preparation

Equality Trust에서 기부금을 받고 제공하는 두 종류의 자료 중 23개 국가의 각종 지표를 비교한 자료에 World Bank에서 발표하는 GDP자료를 추가하여 읽어들이면,

library(knitr)
load("Inequality_Index_HS.rda")
data.full <- read.csv("../data/international-inequality_GDP.csv", stringsAsFactors = FALSE)
str(data.full)
## 'data.frame':    23 obs. of  30 variables:
##  $ Country                          : chr  "Australia" "Austria" "Belgium" "Canada" ...
##  $ Income.inequality                : num  7 4.82 4.6 5.63 4.3 3.72 5.6 5.2 6.2 6.05 ...
##  $ Trust                            : num  39.9 33.9 30.7 38.8 66.5 58 22.2 34.8 23.7 35.2 ...
##  $ Life.expectancy                  : num  79.2 78.5 78.8 79.3 76.6 78 79 78.3 78.3 77 ...
##  $ Infant.mortality                 : num  4.9 4.8 5 5.3 5.3 3.7 4.4 4.4 5 5.9 ...
##  $ Obesity                          : num  18.4 14.5 13.5 12.8 15 ...
##  $ Mental.illness                   : num  23 NA 12 19.9 NA NA 18.4 9.1 NA NA ...
##  $ Maths.and.literacy.scores        : num  524 498 518 530 503 ...
##  $ Teenage.births                   : num  18.4 14 9.9 20.2 8.1 9.2 9.3 13.1 11.8 18.7 ...
##  $ Homicides                        : num  16.9 11.6 13 17.3 12.7 28.2 21.5 13.7 13.9 8.6 ...
##  $ Imprisonment..log.               : num  4.61 4.52 4.28 4.77 4.17 4.11 4.5 4.51 3.33 4.17 ...
##  $ Social.mobility                  : num  NA NA NA 0.14 0.14 0.15 NA 0.17 NA NA ...
##  $ Index.of.health...social_problems: num  0.07 0.01 -0.23 -0.07 -0.19 -0.43 0.05 -0.06 0.38 0.25 ...
##  $ Child.overweight                 : num  NA 11.9 10.4 19.5 10.3 13.3 11.2 11.3 16 12.1 ...
##  $ Drugs.index                      : num  1.71 -0.02 -0.18 0.61 -0.09 -0.88 -0.35 -0.3 -0.99 -0.03 ...
##  $ Calorie.intake                   : int  3142 3753 3632 3167 3405 3197 3576 3395 3687 3656 ...
##  $ Public.health.expenditure        : num  67.9 69.3 71.7 70.8 82.4 75.6 76 74.9 56 76 ...
##  $ Child.wellbeing                  : num  -0.21 -0.07 0.05 0.04 0.21 0.34 -0.17 -0.01 -0.04 -0.04 ...
##  $ Maths.education.science.score    : num  525 496 515 526 494 ...
##  $ Child.conflict                   : num  NA 0.31 0.33 0.24 -0.14 -1.25 0.59 -0.7 0.4 -0.06 ...
##  $ Foreign.aid                      : num  0.25 0.52 0.53 0.34 0.81 0.47 0.47 0.35 0.24 0.41 ...
##  $ Recycling                        : num  7.4 NA NA NA NA NA 6 3.4 NA NA ...
##  $ Peace.index                      : num  1.66 1.48 1.49 1.48 1.38 1.45 1.73 1.52 1.79 1.4 ...
##  $ Maternity.leave                  : int  0 16 15 17 18 18 16 14 17 18 ...
##  $ Advertising                      : num  1.24 0.97 0.82 0.77 0.75 0.9 0.71 0.99 1.04 1 ...
##  $ Police                           : int  304 305 357 186 192 160 NA 303 NA NA ...
##  $ Social.expenditure               : num  17.8 27.5 26.5 17.2 27.6 25.8 29 27.3 19.9 15.8 ...
##  $ Women.s_status                   : num  0.46 -0.81 0.61 0.56 0.83 1.08 -0.17 -0.21 -0.85 -0.21 ...
##  $ Lone.parents                     : int  21 15 12 17 22 19 12 21 3 14 ...
##  $ GDP_WB                           : int  45926 47682 43435 45066 45537 40676 39328 46401 26851 49393 ...

이 자료 중 소득불평등을 나타내는 지표는 5분위계수로서 두번째 컬럼에 Income.inequality라는 이름으로 나와 있고, 건강과 사회문제 지표는 13번째 컬럼에 Index.of.health...social_problems라는 이름으로 주어져 있다. 나라들은 Country라는 변수명으로 첫번째 컬럼에 나와 있다. 그리고, 건강과 사회문제 지표에 결측치들이 있기 때문에 먼저 이 나라들을 제외하고 분석작업을 수행하여야 한다. which()를 이용하여 해당 인덱스를 찾고, 나라명을 추출한다.

(country.na <- which(is.na(data.full$Index.of.health...social_problems)))
## [1] 11 18
data.full$Country[country.na]
## [1] "Israel"    "Singapore"

결측치가 있는 나라를 빼고, 필요한 변수만 챙겨서 새로운 data frame 을 구성하기 위하여 건강과 사회문제 지표의 위치를 찾아보자.

names(data.full)
##  [1] "Country"                          
##  [2] "Income.inequality"                
##  [3] "Trust"                            
##  [4] "Life.expectancy"                  
##  [5] "Infant.mortality"                 
##  [6] "Obesity"                          
##  [7] "Mental.illness"                   
##  [8] "Maths.and.literacy.scores"        
##  [9] "Teenage.births"                   
## [10] "Homicides"                        
## [11] "Imprisonment..log."               
## [12] "Social.mobility"                  
## [13] "Index.of.health...social_problems"
## [14] "Child.overweight"                 
## [15] "Drugs.index"                      
## [16] "Calorie.intake"                   
## [17] "Public.health.expenditure"        
## [18] "Child.wellbeing"                  
## [19] "Maths.education.science.score"    
## [20] "Child.conflict"                   
## [21] "Foreign.aid"                      
## [22] "Recycling"                        
## [23] "Peace.index"                      
## [24] "Maternity.leave"                  
## [25] "Advertising"                      
## [26] "Police"                           
## [27] "Social.expenditure"               
## [28] "Women.s_status"                   
## [29] "Lone.parents"                     
## [30] "GDP_WB"
which(names(data.full) == "Index.of.health...social_problems")
## [1] 13

새로운 data frame 을 data.21 으로 저장하자. 시각적 가독성을 높이기 위하여 자릿수를 조정한다.

options(digits = 2)
v.names <- c("Country", "Income.inequality", "Index.of.health...social_problems", "GDP_WB")
data.21 <- data.full[-c(11, 18), v.names]
names(data.21)[3] <- "Index.HS"
kable(data.21)
Country Income.inequality Index.HS GDP_WB
1 Australia 7.0 0.07 45926
2 Austria 4.8 0.01 47682
3 Belgium 4.6 -0.23 43435
4 Canada 5.6 -0.07 45066
5 Denmark 4.3 -0.19 45537
6 Finland 3.7 -0.43 40676
7 France 5.6 0.05 39328
8 Germany 5.2 -0.06 46401
9 Greece 6.2 0.38 26851
10 Ireland 6.0 0.25 49393
12 Italy 6.6 -0.12 35463
13 Japan 3.4 -1.26 36319
14 Netherlands 5.3 -0.51 48253
15 New Zealand 6.8 0.29 37679
16 Norway 3.8 -0.63 65615
17 Portugal 8.0 1.18 28760
19 Spain 5.5 -0.30 33629
20 Sweden 4.0 -0.83 45297
21 Switzerland 5.7 -0.46 59540
22 UK 7.2 0.79 40233
23 USA 8.6 2.02 54630

Plots

우선 소득불평등과 건강 및 사회문제 지표의 관계를 대략적으로 살펴보면,

Index_inequality.df <- data.21[c("Income.inequality", "Index.HS")]
# str(Index_inequality.df)
plot(Index_inequality.df)

cor.1 <- cor(data.21["Income.inequality"], data.21["Index.HS"])
cor.1
##                   Index.HS
## Income.inequality     0.87

매우 높은 양의 상관관계(r = 0.87) 가 관찰됨을 알 수 있다. 자주 사용하는 data.21[c("Income.inequality", "Index.HS")]를 간단한 R 오브젝트로 assign하여 반복 사용하고 있다. cor()에도 data frame을 사용하면 어떻게 되는지 다음 결과와 비교해 보자.

cor(Index_inequality.df)
##                   Income.inequality Index.HS
## Income.inequality              1.00     0.87
## Index.HS                       0.87     1.00

각 점이 어느 나라를 나타내는지 표시하기 위하여 text() 를 활용하자. 동그라미 대신 까만 점으로 표시하고, 나라 이름을 올려보자.

(Country <- data.21[, "Country"])
##  [1] "Australia"   "Austria"     "Belgium"     "Canada"      "Denmark"    
##  [6] "Finland"     "France"      "Germany"     "Greece"      "Ireland"    
## [11] "Italy"       "Japan"       "Netherlands" "New Zealand" "Norway"     
## [16] "Portugal"    "Spain"       "Sweden"      "Switzerland" "UK"         
## [21] "USA"
(Country.2 <- data.21["Country"])
##        Country
## 1    Australia
## 2      Austria
## 3      Belgium
## 4       Canada
## 5      Denmark
## 6      Finland
## 7       France
## 8      Germany
## 9       Greece
## 10     Ireland
## 12       Italy
## 13       Japan
## 14 Netherlands
## 15 New Zealand
## 16      Norway
## 17    Portugal
## 19       Spain
## 20      Sweden
## 21 Switzerland
## 22          UK
## 23         USA
(Country.3 <- data.21["Country"]$Country)
##  [1] "Australia"   "Austria"     "Belgium"     "Canada"      "Denmark"    
##  [6] "Finland"     "France"      "Germany"     "Greece"      "Ireland"    
## [11] "Italy"       "Japan"       "Netherlands" "New Zealand" "Norway"     
## [16] "Portugal"    "Spain"       "Sweden"      "Switzerland" "UK"         
## [21] "USA"
str(Country)
##  chr [1:21] "Australia" "Austria" "Belgium" "Canada" ...
str(Country.2)
## 'data.frame':    21 obs. of  1 variable:
##  $ Country: chr  "Australia" "Austria" "Belgium" "Canada" ...
str(Country.3)
##  chr [1:21] "Australia" "Austria" "Belgium" "Canada" ...
plot(Index_inequality.df, pch = 20)
text(Index_inequality.df, labels = Country)

text label의 위치 기본값은 바로 점 위임을 알 수 있다. 위치 선정에 가능한 값들을 넣어보자.

plot(Index_inequality.df, pch = 20)
text(Index_inequality.df, labels = Country, pos = 1)

plot(Index_inequality.df, pch = 20)
text(Index_inequality.df, labels = Country, pos = 2)

plot(Index_inequality.df, pch = 20)
text(Index_inequality.df, labels = Country, pos = 3)

plot(Index_inequality.df, pch = 20)
text(Index_inequality.df, labels = Country, pos = 4)

우선 x-축과 y-축의 범위를 xlim = c(3, 9), ylim = c(-1.5, 2.5)로 하여 미국과 일본의 라벨이 도표 밖으로 나가지 않게 하자. pos = 4로 하고 cex = 0.8로 하여 글자 크기를 줄여보면,

plot(Index_inequality.df, pch = 20, xlim = c(3, 9), ylim = c(-1.5, 2.5))
text(Index_inequality.df, labels = Country, pos = 4, cex = 0.8)

오스트리아, 덴마크, 독일, 네덜란드의 라벨만 점 왼편에 위치시켜 보자. 각 인덱스를 찾아보면,

which(Country %in% c("Austria", "Denmark", "Germany", "Netherlands"))
## [1]  2  5  8 13
text.left <- which(Country %in% c("Austria", "Denmark", "Germany", "Netherlands"))
text.left
## [1]  2  5  8 13
text.right <- setdiff(1:nrow(data.21), text.left)
text.right
##  [1]  1  3  4  6  7  9 10 11 12 14 15 16 17 18 19 20 21
pos.text <- ifelse(1:nrow(data.21) %in% text.left, 2, 4)
plot(Index_inequality.df, pch = 20, col = "red", xlim = c(3, 9), ylim = c(-1.5, 2.5))
text(Index_inequality.df, labels = Country, pos = pos.text, cex = 0.8)

독일의 라벨을 위로 붙이면 보기가 나아질 것으로 생각되므로,

which(Country %in% "Germany")
## [1] 8
text.up <- which(Country %in% "Germany")
text.up
## [1] 8
text.left <- setdiff(1:nrow(data.21), c(text.right, text.up))
text.left
## [1]  2  5 13
pos.text <- ifelse(1:nrow(data.21) %in% text.up, 3, ifelse(1:nrow(data.21) %in% text.left, 2, 4))

이제 조정된 text 외에 x-축과 y-축에 적절한 라벨과 메인 타이틀을 넣어보자.

plot(Index_inequality.df, pch = 20, col = "red", xlim = c(3, 9), ylim = c(-1.5, 2.5), ann = FALSE)
text(Index_inequality.df, labels = Country, pos = pos.text, cex = 0.8)
main.title <- "Income Inequality vs Index of Health and Social Problems" 
x.lab <- "Income Inequality (5th Ratio)"
y.lab <- "Index of Health and Social Problems"
title(main = main.title, xlab = x.lab, ylab = y.lab)

건강 및 사회문제 지표의 경우 어느 방향이 좋은지 알 수 없으므로 친절하게 도표의 주변에(margin)에 알려주려면,

plot(Index_inequality.df, pch = 20, col = "red", xlim = c(3, 9), ylim = c(-1.5, 2.5), ann = FALSE)
text(Index_inequality.df, labels = Country, pos = pos.text, cex = 0.8)
main.title <- "Income Inequality vs Index of Health and Social Problems" 
x.lab <- "Income Inequality (5th Ratio)"
y.lab <- "Index of Health and Social Problems"
title(main = main.title, xlab = x.lab, ylab = y.lab)
mtext(c("Better", "Worse"), side = 2, at = c(-1.8, 2.8), las = 1)

상관계수를 텍스트로 그림 안에 넣어주고 여기까지 작업한 내용을 별도의 파일로 저장해 놓으려면,

plot(Index_inequality.df, pch = 20, col = "red", xlim = c(3, 9), ylim = c(-1.5, 2.5), ann = FALSE)
text(Index_inequality.df, labels = Country, pos = pos.text, cex = 0.8)
main.title <- "Income Inequality vs Index of Health and Social Problems" 
x.lab <- "Income Inequality (5th Ratio)"
y.lab <- "Index of Health and Social Problems"
title(main = main.title, xlab = x.lab, ylab = y.lab)
mtext(c("Better", "Worse"), side = 2, at = c(-1.8, 2.8), las = 1)
text(x = 5, y = 1.5, labels = paste("r =", round(cor(Index_inequality.df[1], Index_inequality.df[2]), digits = 2)))

# dev.copy(png, file = "../pics/inequality_health_social_en_72dpi.png", width = 640, height = 480)
# dev.off()

선형회귀선을 추가하여 대체적인 추세를 보려면 lm()을 이용하되, x, y의 순서를 제대로 바꿔야 함에 유의.

plot(Index_inequality.df, pch = 20, col = "red", xlim = c(3, 9), ylim = c(-1.5, 2.5), ann = FALSE)
text(Index_inequality.df, labels = Country, pos = pos.text, cex = 0.8)
main.title <- "Income Inequality vs Index of Health and Social Problems" 
x.lab <- "Income Inequality (5th Ratio)"
y.lab <- "Index of Health and Social Problems"
title(main = main.title, xlab = x.lab, ylab = y.lab)
mtext(c("Better", "Worse"), side = 2, at = c(-1.8, 2.8), las = 1)
text(x = 5, y = 1.5, labels = paste("r =", round(cor(Index_inequality.df[1], Index_inequality.df[2]), digits = 2)))
lm.ineq <- lm(Index.HS ~ Income.inequality, data = Index_inequality.df)
# lm.ineq <- lm(Index_inequality.df[2:1])
abline(lm.ineq$coef, col = "blue")

GDP와 건강 및 사회문제 지수

Index_GDP.df <- data.21[c("GDP_WB", "Index.HS")]
text.left.2 <- which(Country %in% c("Canada", "Belgium", "Australia"))
text.right.2 <- setdiff(1:nrow(data.21), c(text.left.2))
pos.text.2 <- ifelse(1:nrow(data.21) %in% text.left.2, 2, 4)
plot(Index_GDP.df, pch = 20, col = "red", xlim = c(25000, 70000), ylim = c(-1.5, 2.5), xaxt = "n", ann = FALSE)
axis(side = 1, at = seq(30000, 70000, by = 10000), labels = paste(3:7, "만", sep = ""))
text(Index_GDP.df, labels = Country, pos = pos.text.2, cex = 0.8)
text(x = 40000, y = 2, labels = paste("r =", round(cor(Index_GDP.df[1], Index_GDP.df[2]), digits = 2)), cex = 1.2)
main.title.2 <- "GDP vs Index of Health and Social Problems"
x.lab.2 <- "GDP (Thousand Dollars)"
y.lab.2 <- "Index of Health and Social Problems"
title(main = main.title.2, xlab = x.lab.2, ylab = y.lab.2)
mtext(c("Better", "Worse"), side = 2, at = c(-1.8, 2.8), las = 1)

# dev.copy(png, file = "../pics/GDP_health_social_en_72dpi.png", width = 640, height = 480)
# dev.off()

한글화

국가명을 한글로 만들어 Country.kr로 저장하자.

Country.kr<-c("호주", "오스트리아", "벨기에", "캐나다", "덴마크",
"핀란드", "프랑스", "독일", "그리스", "아일랜드", "이탈리아",
"일본", "네덜란드", "뉴질랜드", "노르웨이", "포르투갈",
"스페인", "스웨덴", "스위스", "영국", "미국")
# library(extrafont)
# par(family = "HCR Dotum")
plot(Index_inequality.df, pch = 20, col = "red", xlim = c(3, 9), ylim = c(-1.5, 2.5), ann = FALSE)
text(Index_inequality.df[text.right, ], labels = Country.kr[text.right], pos = 4, cex = 0.8)
text(Index_inequality.df[text.left, ], labels = Country.kr[text.left], pos = 2, cex = 0.8)
text(Index_inequality.df[text.up, ], labels = Country.kr[text.up], pos = 3, cex = 0.8)
main.title.kr <- "소득불평등과 건강 및 사회문제 지수"
x.lab.kr <- "소득불평등(소득5분위계수)"
y.lab.kr <- "건강 및 사회문제 지수"
title(main = main.title.kr, xlab = x.lab.kr, ylab = y.lab.kr)
mtext(c("좋음", "나쁨"), side = 2, at = c(-1.8, 2.8), las = 1)

상관계수 r = 0.87 를 도표 안에 표시하고 별도의 파일로 출력하려면,

# par(family = "HCR Dotum")
plot(Index_inequality.df, pch = 20, col = "red", xlim = c(3, 9), ylim = c(-1.5, 2.5), ann = FALSE)
text(Index_inequality.df, labels = Country.kr, pos = pos.text, cex = 0.8)
main.title.kr <- "소득불평등과 건강 및 사회문제 지수"
x.lab.kr <- "소득불평등(소득5분위계수)"
y.lab.kr <- "건강 및 사회문제 지수"
title(main = main.title.kr, xlab = x.lab.kr, ylab = y.lab.kr)
mtext(c("좋음", "나쁨"), side = 2, at = c(-1.8, 2.8), las = 1)
text(x = 5, y = 1.5, labels = paste("r =", round(cor(Index_inequality.df[1], Index_inequality.df[2]), digits = 2)))

# dev.copy(png, file = "../pics/inequality_health_social_72dpi.png", width = 640, height = 480)
# dev.off()

선형회귀선을 이번에는 lsfit을 이용하여 삽입

# par(family = "HCR Dotum")
plot(Index_inequality.df, pch = 20, col = "red", xlim = c(3, 9), ylim = c(-1.5, 2.5), ann = FALSE)
text(Index_inequality.df, labels = Country.kr, pos = pos.text, cex = 0.8)
main.title.kr <- "소득불평등과 건강 및 사회문제 지수"
x.lab.kr <- "소득불평등(소득5분위계수)"
y.lab.kr <- "건강 및 사회문제 지수"
title(main = main.title.kr, xlab = x.lab.kr, ylab = y.lab.kr)
mtext(c("좋음", "나쁨"), side = 2, at = c(-1.8, 2.8), las = 1)
text(x = 5, y = 1.5, labels = paste("r =", round(cor(Index_inequality.df[1], Index_inequality.df[2]), digits = 2)))
lsfit.ineq <- lsfit(x = Index_inequality.df[, 1], y = Index_inequality.df[, 2])
abline(lsfit.ineq$coefficients, col = "blue")

GDP와의 관계

# par(family = "HCR Dotum")
Index_GDP.df <- data.21[c("GDP_WB", "Index.HS")]
text.left.2 <- which(Country %in% c("Canada", "Belgium", "Australia"))
text.right.2 <- setdiff(1:nrow(data.21), c(text.left.2))
pos.text.2 <- ifelse(1:nrow(data.21) %in% text.left.2, 2, 4)
plot(Index_GDP.df, pch = 20, col = "red", xlim = c(25000, 70000), ylim = c(-1.5, 2.5), xaxt = "n", ann = FALSE)
axis(side = 1, at = seq(30000, 70000, by = 10000), labels = paste(3:7, "만", sep = ""))
text(Index_GDP.df, labels = Country.kr, pos = pos.text.2, cex = 0.8)
text(x = 40000, y = 2, labels = paste("r =", round(cor(Index_GDP.df[1], Index_GDP.df[2]), digits = 2)), cex = 1.2)
main.title.2.kr <- "GDP와 건강 및 사회문제 지수"
x.lab.2.kr <- "GDP(달러)"
y.lab.2.kr <- "건강 및 사회문제 지수"
title(main = main.title.2.kr, xlab = x.lab.2.kr, ylab = y.lab.2.kr)
mtext(c("좋음", "나쁨"), side = 2, at = c(-1.8, 2.8), las = 1)

# dev.copy(png, file = "../pics/GDP_health_social_72dpi.png", width = 640, height = 480)
# dev.off()

미국의 경우

xlsx 패키지를 이용하여 자료를 읽어들인다.

# data.usa <- read.xlsx("../data/USA-inequality.xls", 1, stringsAsFactors = FALSE)
str(data.usa)
## 'data.frame':    50 obs. of  20 variables:
##  $ State                            : chr  "Alabama" "Alaska" "Arizona" "Arkansas" ...
##  $ State.Abbrev                     : chr  "AL" "AK" "AZ" "AR" ...
##  $ Income.Inequality                : num  0.475 0.402 0.45 0.458 0.475 ...
##  $ Trust                            : num  23 NA 47 29 43 46 49 NA 37 38 ...
##  $ Life.expectancy                  : num  74.6 76.7 77.5 75.1 78.3 ...
##  $ Infant.mortality                 : num  9.1 5.5 6.4 8.3 5.5 ...
##  $ Obesity                          : num  32 30 28.5 31 31 21.5 26.5 27 27.5 30.5 ...
##  $ Mental.health                    : num  3.3 2.8 2.2 3.2 3.3 ...
##  $ Maths.and.literacy.scores        : num  258 268 263 262 259 ...
##  $ Teenage.births                   : num  62.9 42.4 69.1 68.5 48.5 ...
##  $ Homicides                        : num  78.9 85.6 80.4 56.1 60.5 ...
##  $ Imprisonment                     : num  509 413 507 415 478 357 372 429 447 502 ...
##  $ Index.of.health...social.problems: num  1.385 0.137 0.212 0.948 0.327 ...
##  $ Overweight.children              : num  35 31 30 33 30 22 27 35 32 32 ...
##  $ Child.wellbeing                  : num  8.5 4.4 4.9 9.3 -3.4 ...
##  $ Women.s.status                   : num  -0.932 0.74 -0.147 -1.318 0.969 ...
##  $ Juvenile.homicides               : num  12 8 7 6 10 4 4 0 NA 8 ...
##  $ High.school.drop.outs            : num  24.7 11.7 19 24.7 23.2 ...
##  $ Child.mental.illness             : num  11.5 8.2 8.7 11.8 7.5 ...
##  $ Pugnacity                        : num  41.8 NA 36.3 38.4 37.7 ...

당장 필요한 변수들만 모아서 data frame으로 재구성한다. 변수명 설정에 유의한다.

data.usa.1 <- data.frame(Gini = data.usa$Income.Inequality,  HS.index = data.usa$Index.of.health...social.problems)
str(data.usa.1)
## 'data.frame':    50 obs. of  2 variables:
##  $ Gini    : num  0.475 0.402 0.45 0.458 0.475 ...
##  $ HS.index: num  1.385 0.137 0.212 0.948 0.327 ...
Abb <- data.usa$State.Abbrev
options(digits = 3)
data.usa.1
##     Gini HS.index
## 1  0.475   1.3849
## 2  0.402   0.1371
## 3  0.450   0.2122
## 4  0.458   0.9480
## 5  0.475   0.3270
## 6  0.438  -0.5072
## 7  0.477  -0.6597
## 8  0.429   0.1334
## 9  0.470   0.3596
## 10 0.461   0.8956
## 11 0.434  -0.3880
## 12 0.427  -0.4291
## 13 0.456   0.2065
## 14 0.424   0.3698
## 15 0.418  -0.8948
## 16 0.435  -0.4423
## 17 0.468   0.8738
## 18 0.483   1.5948
## 19 0.434  -0.7692
## 20 0.434   0.1873
## 21 0.463  -0.9586
## 22 0.440   0.3494
## 23 0.426  -1.2160
## 24 0.478   1.6915
## 25 0.449   0.3917
## 26 0.436  -0.9058
## 27 0.424  -0.5831
## 28 0.436   0.8032
## 29 0.414  -1.2417
## 30 0.460  -0.4022
## 31 0.460   0.5636
## 32 0.499  -0.1790
## 33 0.452   0.4942
## 34 0.429  -1.1450
## 35 0.441   0.0583
## 36 0.455   0.4935
## 37 0.438  -0.3459
## 38 0.452  -0.0155
## 39 0.457  -0.3891
## 40 0.454   0.8992
## 41 0.434  -0.7585
## 42 0.465   0.7881
## 43 0.470   0.9299
## 44 0.410  -0.7090
## 45 0.423  -1.1828
## 46 0.449  -0.0550
## 47 0.436  -0.5156
## 48 0.468   0.4817
## 49 0.413  -0.4731
## 50 0.428  -0.5512

간단한 산점도를 그리고, 추가 작업을 생각한다.

plot(data.usa.1)

x-축과 y-축의 범위를 설정하고, pch = 20으로 다시 그린다.

plot(data.usa.1, pch = 20, xlim = c(0.39, 0.51), ylim = c(-1.5, 2.0))

각 주의 약칭을 새겨넣는다.

plot(data.usa.1, pch = 20, xlim = c(0.39, 0.51), ylim = c(-1.5, 2.0))
text(data.usa.1, labels = Abb, pos = 4)

겹쳐보이는 주의 약칭들로부터 인덱스를 추출한다.

which(Abb %in% c("VT", "ME", "NE", "WA", "VA", "HI", "RI", "SC", "AR", "NC", "GA", "KY"))
##  [1]  4 10 11 17 19 27 33 39 40 45 46 47

점 왼쪽에 약칭을 넣을 주들의 인덱스를 저장한다. 나머지 인덱스는 오른쪽에 넣을 것으로 따로 저장한다.

text.left.us <- which(Abb %in% c("VT", "ME", "NE", "WA", "VA", "HI", "RI", "SC", "AR", "NC", "GA", "KY"))
text.right.us <- setdiff(1:nrow(data.usa.1), text.left.us)
pos.text.us <- ifelse(1:nrow(data.usa.1) %in% text.left.us, 2, 4)

왼쪽, 오른쪽 위치를 조정한 주 약칭을 다시 넣는다.

plot(data.usa.1, pch = 20, col = "red", xlim = c(0.39, 0.51), ylim = c(-1.5, 2.0))
text(data.usa.1, labels = Abb, pos = pos.text.us)

점 아래에 약칭을 넣을 주들의 인덱스를 찾는다. 왼쪽 인덱스, 오른쪽 인덱스에서 조정한다.

text.down.us <- which(Abb %in% c("WA", "AR", "GA", "MN"))
which(text.left.us %in% text.down.us)
## [1]  1  2 12
text.left.us <- setdiff(text.left.us, text.down.us)
text.right.us <- setdiff(text.right.us, text.down.us)
pos.text.us <- ifelse(1:nrow(data.usa.1) %in% text.down.us, 1, ifelse(1:nrow(data.usa.1) %in% text.left.us, 2, 4))

약칭 위치를 아래로 조정한 산점도를 다시 그린다.

plot(data.usa.1, pch = 20, col = "red", xlim = c(0.39, 0.51), ylim = c(-1.5, 2.0))
text(data.usa.1, labels = Abb, pos = pos.text.us)

상관계수를 추가한다.

plot(data.usa.1, pch = 20, col = "red", xlim = c(0.39, 0.51), ylim = c(-1.5, 2.0))
text(data.usa.1, labels = Abb, pos = pos.text.us)
cor.us <- cor(data.usa.1$HS.index, data.usa.1$Gini)
text(x = 0.42, y = 1.5, labels = paste("r =", round(cor.us, digits = 2)), col = "red", cex = 1.2)

단순회귀선을 추가한다.

plot(data.usa.1, pch = 20, col = "red", xlim = c(0.39, 0.51), ylim = c(-1.5, 2.0))
text(data.usa.1, labels = Abb, pos = pos.text.us)
text(x = 0.42, y = 1.5, labels = paste("r =", round(cor.us, digits = 2)), col = "red", cex = 1.2)
# lm.ineq.us <- lm(HS.index ~ Gini, data = data.usa.1)
lm.ineq.us <- lm(data.usa.1[2:1])
abline(lm.ineq.us$coef, col = "blue")

# abline(lm(HS.index ~ Gini, data = data.usa.1)$coef)

주제목을 추가하고, xlab, ylab을 수정한다. 수직축의 의미를 명확히 한다.

plot(data.usa.1, pch = 20, col = "red", xlim = c(0.39, 0.51), ylim = c(-1.5, 2.0), ann = FALSE)
text(data.usa.1, labels = Abb, pos = pos.text.us)
text(x = 0.42, y = 1.5, labels = paste("r =", round(cor.us, digits = 2)), col = "red", cex = 1.2)
abline(lm.ineq.us$coef, col = "blue")
mtext(c("Better", "Worse"), side = 2, at = c(-1.8, 2.3), las = 1)
main.title.us <- "Income Inequality vs Health and Social Index (USA)"
x.lab.us <- "Gini Coefficients"
y.lab.us <- "Index of Health and Social Problems"
title(main = main.title.us, xlab = x.lab.us, ylab = y.lab.us)