1 동기부여

오래전에 경제지 The Economist에서 한 그래프를 본적이 있었습니다.

development_report

ggplot2 패키지가 시각화에 특화되었다고 하는데, 한번쯤은 증명하고 싶었습니다. 쉽게 구현은 되는 것일까? 코드상의 어려움은 없는 것일까? 반신반의 하던 중 관련된 튜토리얼이 있어서 부분 한글화 하기로 하였습니다. 전체 내용은 아래 링크를 참고하기를 바랍니다.

2 데이터 내려받기

데이터는 해당 EconomicsData 클릭하면 다운로드 받을 수 있습니다.

3 패키지 설치 및 로드하기

R 에서 데이터 시각화와 전처리 패키지인 tidyverse, ggrepel, grid를 설치합니다.

# install.packages("tidyverse")
library(tidyverse)
library(ggrepel)
library(grid)
library(ggthemes)

4 데이터 불러오기

데이터를 불러옵니다. 현재 저장된 파일 경로에 주의하시기를 바랍니다.

economicsData <- read_csv("EconomistData.csv")
glimpse(economicsData)
## Observations: 173
## Variables: 5
## $ Country  <chr> "Afghanistan", "Albania", "Algeria", "Angola", "Argenti…
## $ HDI.Rank <dbl> 172, 70, 96, 148, 45, 86, 2, 19, 91, 53, 42, 146, 47, 6…
## $ HDI      <dbl> 0.398, 0.739, 0.698, 0.486, 0.797, 0.716, 0.929, 0.885,…
## $ CPI      <dbl> 1.5, 3.1, 2.9, 2.0, 3.0, 2.6, 8.8, 7.8, 2.4, 7.3, 5.1, …
## $ Region   <chr> "Asia Pacific", "East EU Cemt Asia", "MENA", "SSA", "Am…
  • 데이터는 173개 국가에 대한 데이터입니다.
  • 데이터 변수의 뜻은 아래와 같습니다.
    • Country: 국가
    • HDI.Rank: 인간개발지수 순위(Human Development Index)
    • HDI: 인간개발지수(Human Development Index)
    • CPI: 부패인식지수(Corruption Perceptions Index)
    • Region: 대륙

5 단계별 시각화

5.1 산점도 그리기

ggplot(economicsData, aes(x = CPI, y = HDI, color = Region)) + 
  geom_point()

5.2 회귀선 그리기

ggplot(economicsData, aes(x = CPI, y = HDI, color = Region)) + 
  geom_smooth(mapping = aes(linetype = "r2"), 
              method = "lm", 
              formula = y ~ x + log(x), 
              se = FALSE, 
              color = "red") + 
  geom_point(shape = 1, size = 2.5, stroke = 1.25)

5.2.1 주요 포인트

  1. 산점도를 두번째 함수로 작업한 이유는, 빨간색 선위에, 국가들을 표시하기 위해서입니다.
  2. 산점도의 모양과 크기에 변화를 주었습니다.

5.3 주요국가 명기

mainCountries <- c("Russia", "Venezuela", "Iraq", "Myanmar", "Sudan",
                   "Afghanistan", "Congo", "Greece", "Argentina", "Brazil",
                   "India", "Italy", "China", "South Africa", "Spane",
                   "Botswana", "Cape Verde", "Bhutan", "Rwanda", "France",
                   "United States", "Germany", "Britain", "Barbados", "Norway", "Japan",
                   "New Zealand", "Singapore", "Korea (South)")

ggplot(economicsData, aes(x = CPI, y = HDI, color = Region)) + 
  geom_smooth(mapping = aes(linetype = "r2"), 
              method = "lm", 
              formula = y ~ x + log(x), 
              se = FALSE, 
              color = "red") + 
  geom_point(shape = 1, size = 2.5, stroke = 1.25) + 
  geom_text_repel(aes(label = Country),
                   color = "gray20",
                   data = filter(economicsData, Country %in% mainCountries),
                   force = 10)

  • 나중에 각나라의 값을 한글화로 하고 싶어지기는 하네요.

5.4 Region 변수의 값을 변환

factor()함수를 활용하여 범주의 값을 변환합니다.

economicsData$Region <- factor(economicsData$Region,
                     levels = c("EU W. Europe",
                                "Americas",
                                "Asia Pacific",
                                "East EU Cemt Asia",
                                "MENA",
                                "SSA"),
                     labels = c("OECD",
                                "Americas",
                                "Asia &\nOceania",
                                "Central &\nEastern Europe",
                                "Middle East &\nnorth Africa",
                                "Sub-Saharan\nAfrica"))

ggplot(economicsData, aes(x = CPI, y = HDI, color = Region)) + 
  geom_smooth(mapping = aes(linetype = "r2"), 
              method = "lm", 
              formula = y ~ x + log(x), 
              se = FALSE, 
              color = "red") + 
  geom_point(shape = 1, size = 2.5, stroke = 1.25) + 
  geom_text_repel(aes(label = Country),
                   color = "gray20",
                   data = filter(economicsData, Country %in% mainCountries),
                   force = 10)  

  • 우선 영어로 작업을 진행합니다. 추후에 한글화로 변환 후, Windows환경과 Mac환경에서 나누어 명기하도록 할 예정입니다.

5.5 그래프의 제목과 축 제목 수정

scale_x_continous() & scale_y_continuous() 함수를 활용하여 그래프의 범위와 함께 제목을 수정하려고 합니다.

ggplot(economicsData, aes(x = CPI, y = HDI, color = Region)) + 
  geom_smooth(mapping = aes(linetype = "r2"), 
              method = "lm", 
              formula = y ~ x + log(x), 
              se = FALSE, 
              color = "red") + 
  geom_point(shape = 1, size = 2.5, stroke = 1.25) + 
  geom_text_repel(aes(label = Country),
                   color = "gray20",
                   data = filter(economicsData, Country %in% mainCountries),
                   force = 10) +
  scale_x_continuous(name = "Corruption Perceptions Index, 2011 (10=least corrupt)",
                     limits = c(.9, 10.5),
                     breaks = 1:10) +
  scale_y_continuous(name = "Human Development Index, 2011 (1=Best)",
                     limits = c(0.2, 1.0),
                     breaks = seq(0.2, 1.0, by = 0.1))

5.6 Region 색상 재정의 (옵션)

색상은 기본적으로 Default로 지정됩니다. 우선 Manual을 알려드리면, 응용은 충분히 가능합니다.

ggplot(economicsData, aes(x = CPI, y = HDI, color = Region)) + 
  geom_smooth(mapping = aes(linetype = "r2"), 
              method = "lm", 
              formula = y ~ x + log(x), 
              se = FALSE, 
              color = "red") + 
  geom_point(shape = 1, size = 2.5, stroke = 1.25) + 
  geom_text_repel(aes(label = Country),
                   color = "gray20",
                   data = filter(economicsData, Country %in% mainCountries),
                   force = 10) +
  scale_x_continuous(name = "Corruption Perceptions Index, 2011 (10=least corrupt)",
                     limits = c(.9, 10.5),
                     breaks = 1:10) +
  scale_y_continuous(name = "Human Development Index, 2011 (1=Best)",
                     limits = c(0.2, 1.0),
                     breaks = seq(0.2, 1.0, by = 0.1)) + 
  scale_color_manual(name = "", 
                     values = c("#17FF92", 
                                "#0E34EB", 
                                "#FF00BF", 
                                "#EB7609", 
                                "#FFFD0C", 
                                "#D51BEB"))

5.7 범례 서식 수정

그래프의 테마를 별도로 지정하면 데이터의 배경 및 범례 서식을 수정한다. - 우선 범례가 크게 두개가 존재한다. (1) 회귀선에 대한 범례 (2) Region에 대한 범례

5.7.1 회귀선에 대한 범례

회귀선 범례를 수정하기에 앞서서 회귀선 식의 값을 우선 구하고, 반영한다.

lmR2 <- summary(lm(HDI ~ CPI + log(CPI), data = economicsData))$r.squared
lmR2 <- paste0(format(lmR2, digits = 2), "%")

ggplot(economicsData, aes(x = CPI, y = HDI, color = Region)) + 
  geom_smooth(mapping = aes(linetype = "r2"), 
              method = "lm", 
              formula = y ~ x + log(x), 
              se = FALSE, 
              color = "red") + 
  geom_point(shape = 1, size = 2.5, stroke = 1.25) + 
  geom_text_repel(aes(label = Country),
                   color = "gray20",
                   data = filter(economicsData, Country %in% mainCountries),
                   force = 10) +
  scale_x_continuous(name = "Corruption Perceptions Index, 2011 (10=least corrupt)",
                     limits = c(.9, 10.5),
                     breaks = 1:10) +
  scale_y_continuous(name = "Human Development Index, 2011 (1=Best)",
                     limits = c(0.2, 1.0),
                     breaks = seq(0.2, 1.0, by = 0.1)) + 
  scale_linetype(name = "", # 범례의 제목 지우기
                 breaks = "r2", 
                 labels = list(bquote(R^2 == .(lmR2))), 
                 guide = guide_legend(override.aes = list(linetype = 1, size = 1.5, color = "red"), order=2)
                 )

5.7.2 Region에 대한 범례 수정

  • 범례 제목을 삭제한 후, 데이터 값을 바꿔준다.
ggplot(economicsData, aes(x = CPI, y = HDI, color = Region)) + 
  geom_smooth(mapping = aes(linetype = "r2"), 
              method = "lm", 
              formula = y ~ x + log(x), 
              se = FALSE, 
              color = "red") + 
  geom_point(shape = 1, size = 2.5, stroke = 1.25) + 
  geom_text_repel(aes(label = Country),
                   color = "gray20",
                   data = filter(economicsData, Country %in% mainCountries),
                   force = 10) +
  scale_x_continuous(name = "Corruption Perceptions Index, 2011 (10=least corrupt)",
                     limits = c(.9, 10.5),
                     breaks = 1:10) +
  scale_y_continuous(name = "Human Development Index, 2011 (1=Best)",
                     limits = c(0.2, 1.0),
                     breaks = seq(0.2, 1.0, by = 0.1)) + 
  scale_linetype(name = "", # 범례의 제목 지우기
                 breaks = "r2", 
                 labels = list(bquote(R^2 == .(lmR2))), 
                 guide = guide_legend(override.aes = list(linetype = 1, size = 1.5, color = "red"), order=2)
                 ) + 
  scale_color_manual(name = "",
                     values = c("#3129FF",
                                "#D51BEB",
                                "#FF2E12",
                                "#EB931A",
                                "#F2583F",
                                "#96503F"), 
                     guide = guide_legend(nrow = 1, order = 1)) + 
  theme(legend.position = "top")

5.8 그래프의 제목, 출처 추가, 그리고 최종 수정하기

  • theme() 옵션에서 범례, 축, 그래프, 글자 등 다양한 범위에서 수정을 할 수가 있습니다.
  • labs() 함수를 사용하여 그래프의 제목 및 출처를 기입할 수 있습니다.
ggplot(economicsData, aes(x = CPI, y = HDI, color = Region)) + 
  geom_smooth(mapping = aes(linetype = "r2"), 
              method = "lm", 
              formula = y ~ x + log(x), 
              se = FALSE, 
              color = "red") + 
  geom_point(shape = 1, size = 2.5, stroke = 1.25) + 
  geom_text_repel(aes(label = Country),
                   color = "gray20",
                   data = filter(economicsData, Country %in% mainCountries),
                   force = 10) +
  scale_x_continuous(name = "Corruption Perceptions Index, 2011 (10=least corrupt)",
                     limits = c(.9, 10.5),
                     breaks = 1:10) +
  scale_y_continuous(name = "Human Development Index, 2011 (1=Best)",
                     limits = c(0.2, 1.0),
                     breaks = seq(0.2, 1.0, by = 0.1)) + 
  scale_linetype(name = "", # 범례의 제목 지우기
                 breaks = "r2", 
                 labels = list(bquote(R^2 == .(lmR2))), 
                 guide = guide_legend(override.aes = list(linetype = 1, size = 1.5, color = "red"), order=2)
                 ) + 
  scale_color_manual(name = "",
                     values = c("#3129FF",
                                "#D51BEB",
                                "#FF2E12",
                                "#EB931A",
                                "#F2583F",
                                "#96503F"), 
                     guide = guide_legend(nrow = 1, order = 1)) + 
  labs(title = "Corruption and Human Development", 
       caption = "Sources: Transparency International: UN Human Development Report(2011)") + 
  theme_calc() + 
  theme(panel.border = element_blank(),
        panel.grid = element_blank(),
        panel.grid.major.y = element_line(color = "gray"),
        text = element_text(color = "gray20"),
        axis.title.x = element_text(face="italic"),
        axis.title.y = element_text(face="italic"),
        legend.position = "top",
        legend.direction = "horizontal",
        legend.box = "horizontal",
        legend.text = element_text(size = 12),
        plot.caption = element_text(hjust=0),
        plot.title = element_text(size = 16, face = "bold"))

6 그래프의 한글화