오래전에 경제지 The Economist에서 한 그래프를 본적이 있었습니다.
ggplot2 패키지가 시각화에 특화되었다고 하는데, 한번쯤은 증명하고 싶었습니다. 쉽게 구현은 되는 것일까? 코드상의 어려움은 없는 것일까? 반신반의 하던 중 관련된 튜토리얼이 있어서 부분 한글화 하기로 하였습니다. 전체 내용은 아래 링크를 참고하기를 바랍니다.
데이터는 해당 EconomicsData 클릭하면 다운로드 받을 수 있습니다.
R 에서 데이터 시각화와 전처리 패키지인 tidyverse, ggrepel, grid를 설치합니다.
# install.packages("tidyverse")
library(tidyverse)
library(ggrepel)
library(grid)
library(ggthemes)
데이터를 불러옵니다. 현재 저장된 파일 경로에 주의하시기를 바랍니다.
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…
ggplot(economicsData, aes(x = CPI, y = HDI, color = Region)) +
geom_point()
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)
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)
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)
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))
색상은 기본적으로 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"))
그래프의 테마를 별도로 지정하면 데이터의 배경 및 범례 서식을 수정한다. - 우선 범례가 크게 두개가 존재한다. (1) 회귀선에 대한 범례 (2) Region에 대한 범례
회귀선 범례를 수정하기에 앞서서 회귀선 식의 값을 우선 구하고, 반영한다.
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)
)
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")
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"))