시각화¶
보고를 위한 그래프 그리기¶
D3.js와 그 외 JS 그래프¶
- D3.js 는 html, javascirpt 로 만들 수 있는 그래프
- R에서는 rCharts 를 이용 html, js를 몰라도 사용 가능
- rChart : JS 라이브러리를 R 에서 직접 사용하게 해주는 패키지
- D3.js 는 인터랙티브 그래프
In [1]:
# rChart 설치 - Github
install.packages('devtools')
In [4]:
# https://github.com/saurfang/rCharts
install_github('saurfang/rCharts', ref='utf8-writelines')
In [3]:
library('devtools')
In [ ]:
# Rcpp 오류시 conda consol에서 설치
conda install -c conda-forge r-rcpp
In [5]:
# 개발자 제공 기본 예제 해보기
library('rCharts')
In [6]:
hair_eye_male <- subset(as.data.frame(HairEyeColor), Sex == 'Male')
n1 <- nPlot(Freq ~ Hair, group='Eye', data=hair_eye_male, type='multiBarChart')
n1
nPlot() : D3.js의 NVD3 라이브러리 기반¶
In [11]:
# 데이터 적재
df <- read.csv('R-ggagi-data/example_studentlist2.csv')
attach(df)
In [12]:
# 산포도 그리기 type='scatterChart'
n1 <- nPlot(data=df, height~weight, group='sex', type='scatterChart')
n1
In [14]:
# 파이 차트 그리기
n2 <- nPlot(data=df, ~bloodtype, type='pieChart')
n2
In [16]:
# 파이 차트 -> 도넛 차트
n2$chart(donut=T)
n2
In [35]:
# 멀티 막대 그래프
# 도수를 자동으로 처리해주지 않음
library('dplyr')
df2 <- df %>%
group_by(bloodtype, sex) %>%
summarise(n=n())
In [36]:
n4 <- nPlot(data=df2, n~bloodtype, group='sex', type='multiBarChart')
n4
In [37]:
# 라인차트
ts <- read.csv('R-ggagi-data/example_ts2.csv')
In [43]:
ts$time <- as.Date(ts$time) # 날짜형으로 변환
ts$time
In [45]:
# filter 조건에 맞게 뽑아오기
ts2 <- ts %>% filter(year == 2014)
head(ts2)
In [54]:
n5 <- nPlot(data=ts2, sales~time, type='lineChart')
n5
# x축 time 값이 이상함 (변경 필요)
In [55]:
# x출 time 값 변환 xAxis()
n5$xAxis(tickFormat = "#!
function(d) {
return d3.time.format('%Y-%m-%d')
(new Date(d*1000*3600*24));
} !#", rotateLabels = -45)
n5
In [56]:
# 누적 영역 차트
ts3 <- read.csv('R-ggagi-data/example_ts3.csv')
head(ts3$time)
In [58]:
ts3$time <- as.Date(ts3$time)
head(ts3$time)
n6 <- nPlot(data=ts3, sales~time, group='product', type='stackedAreaChart')
n6
# x 축 time값 변환 필요
In [59]:
# x축 time 값 변환 xAxis()
n6$xAxis(tickFormat = "#!
function(d) {
return d3.time.format('%Y-%m-%d')
(new Date(d*1000*3600*24));
} !#", rotateLabels = -45)
n6
In [60]:
# 라인포커스 - 2개 그래프, 아래 그래프는 네비게이터
n7 <- nPlot(data=ts3, sales~time, group='product', type='lineWithFocusChart')
n7
# x 축 time값 변환 필요
In [62]:
# x축 time 값 변환 xAxis()
n7$xAxis(tickFormat = "#!
function(d) {
return d3.time.format('%Y-%m-%d')
(new Date(d*1000*3600*24));
} !#", rotateLabels = -15)
n7
In [63]:
head(ts3)
Sankey Diagram 으로 예산 한눈에 보기¶
- 러시아로 출발한 나폴레옹 병력 수 변화 그래프로 유명
- 흐름(Flow) 다이어그램의 한 종류로, 화살표의 너비로 흐름의 양을 비율적으로 표현
설치¶
- https://github.com/timelyportfolio/rCharts_d3_sankey download
- 작업폴더에 libraries/압축풀기
In [64]:
# library load
library('dplyr')
library('rCharts')
In [70]:
# data load - 2015년 예산안
DF <- read.csv('R-ggagi-data/example_2015_expenditure.csv')
str(DF)
In [71]:
# 원본 복사 (raw data 이므로)
DF2 <- DF
In [72]:
# sum.확정안 변수 이름 및 단위 변경( 원 => 천원)
colnames(DF2)[6] <- 'value'
# 단위 변경
DF2['value'] <- round(DF2['value']/1000)
head(DF2)
In [74]:
# 데이터 전처리를 위해 자료 복사
DF3 <- DF2
In [82]:
# Sankey Diagram은 모든 노드 1차원, 각각은 sum으로 합산되어 있어야 함
# 소관명 노드 => 회계명 노드 => 분야명 노드 => 부문명 노드 => 프로그램명 노드 순으로 group_by
sum1 <- DF3 %>% group_by(소관명, 회계명) %>% summarise(sum(value))
sum2 <- DF3 %>% group_by(회계명, 분야명) %>% summarise(sum(value))
sum3 <- DF3 %>% group_by(분야명, 부문명) %>% summarise(sum(value))
sum4 <- DF3 %>% group_by(부문명, 프로그램명) %>% summarise(sum(value))
In [83]:
sum1
In [84]:
sum2
In [85]:
sum3
In [86]:
sum4
In [93]:
# Sankey Diagram은 'source', 'target', 'value' 구성되어야 함
colnames(sum1) <- c("source", "target", "value")
colnames(sum2) <- c("source", "target", "value")
colnames(sum3) <- c("source", "target", "value")
colnames(sum4) <- c("source", "target", "value")
In [99]:
head(sum1)
In [94]:
# 하나의 객체로 bind
sum1 <- as.data.frame(sum1)
sum2 <- as.data.frame(sum2)
sum3 <- as.data.frame(sum3)
sum4 <- as.data.frame(sum4)
DF4 <- rbind(sum1, sum2, sum3, sum4)
In [98]:
head(DF4)
tail(DF4)
In [106]:
# library load
sankeyPlot <- rCharts$new() # rChart 객체 생성
sankeyPlot$setLib('libraries//rCharts_d3_sankey-gh-pages') # rChart 속성 지정
sankeyPlot$setTemplate(script = 'libraries//rCharts_d3_sankey-gh-pages/layouts/chart.html')
In [107]:
# 그래프 속성 지정
sankeyPlot$set(
data = DF4,
nodeWidth = 15,
nodePadding = 13,
layout = 300,
width = 900,
height = 600,
units = "천원",
title = "Sankey Diagram"
)
In [108]:
# 그래프 실행 - 라인두께가 예산 금액
# 예산이 어디로 흘러가는 지 한눈에 알 수 있음
sankeyPlot
작년에 구입한 아파트는 올랐을까?¶
- New York Times Visualization Lab 뉴욕타임즈 시각화 팀
- https://www.nytimes.com/interactive/2014/01/23/business/case-shiller-slider.html
- 미국 지역 / 구입년도 선택하면 집값 변동과 다른 지역의 상대적인 변화도 보여줌
서울 - 구 단위 아파트 가격 변화¶
- DataSet : 국토교통부 실거래가 공개 시스템 데이터 2006~2014
In [109]:
# library load
library(readxl)
library(dplyr)
library(stringr)
library(rCharts)
sprintf() : 데이터 포맷 변경 함수¶
In [140]:
# data load -sprintf()
files <- sprintf("%4d년_%02d월_전국_실거래가_아파트(매매).xls",
rep(2006:2014, each = 12), 1:12)
In [141]:
files
In [142]:
DF <- NULL
In [143]:
# paste0 : 문자열 열결
for(i in 1:length(files)){
t <- read_excel(path=paste0("R-ggagi-data//rawdata/", files[i]), sheet=1, col_names=T)
t <- mutate(t, date=paste0(substr(files[i], 1,4), "-", month=substr(files[i], 7,8), "-10"))
DF <- rbind(DF, t)
}
In [144]:
head(DF)
In [157]:
# 변수명 변경 - 한글 변수명 깨진 경우만
DF2 <- DF #안전하게 새로운 객체에 복사
colnames(DF2) <- c("시군구", "본번", "부번", "단지명", "전용면적", "계약일",
"거래금액", "층", "건축년도", "도로명주소", "date")
In [158]:
# 필요한 데이터 불러오기
DF3 <- data.frame(date=DF2$date, addr=DF2$시군구, val=DF2$거래금액)
head(DF3)
str(DF3)
gsub() : 모든 매치부분을 치환¶
In [164]:
# 데이터 형 변환 전 작업
# chr->int (value값만) 로 바꾸기 전에 val 값에 있는 , 제거해주기 : gsub
DF3$val <- gsub(',','',DF3$val)
In [165]:
head(DF3)
In [166]:
# 데이터 형 변환
# chr->int (value값만)
DF3[['val']] <- as.integer(DF3[['val']])
In [167]:
head(DF3)
In [176]:
# 주소 변환 : 서울특별시 강남구 개포동 -> 강남구
# 서울특별시 강남구 개포동을 나눠서 구만 뽑아오기 - str_split_fixed
City <- str_split_fixed(DF3[,2], " ", 3)
City <- data.frame(City)
head(City)
In [178]:
# 구만 가져와서 세 데이터프레임 생성
DF4 <- data.frame(date=DF3[,1], addr=City[,2], val=DF3[,3])
head(DF4)
In [181]:
# 구별 평균 구하기 - 중앙값, 또는 면적별 평균 등 다양하게
DF5 <- DF4 %>% group_by(date, addr) %>% summarise(mean(val))
head(DF5)
In [182]:
# 최종데이터 정리
colnames(DF5)[3] <- "val"
head(DF5)
In [183]:
# 그래프 그리기
g2 <- rCharts$new()
In [188]:
g2$setLib('R-ggagi-data//libraries/nyt_home')
g2$setTemplate(script = 'R-ggagi-data//libraries/nyt_home/layouts/nyt_home.html')
In [189]:
g2$set(
description = "This data comes from the 'rt.molit.go.kr' dataset",
data = DF5,
groups = "addr"
)
In [190]:
g2
In [192]:
# html로 출력
# cat(g2$html())
In [ ]:
'R' 카테고리의 다른 글
[R] 확률 실전예제--------주피터파일--------- (0) | 2020.07.13 |
---|---|
[R] 확률 (0) | 2020.07.10 |
[R] R 필수 패키지 설치 및 기초 (0) | 2020.07.08 |
[R] 데이터 시각화 및 EDA (0) | 2020.07.08 |
[R] 데이터 시각화 (0) | 2020.07.08 |
댓글