본문 바로가기
공부/R & Python

5-3. R 그래픽-3D, 히트맵

by 드인 2020. 2. 15.

5-3. R 그래픽-3D, 히트맵


1) R 추가패키지

- 추가패키지 설치 (install.packages)

setwd("D:/R files/week5__3")

install.packages('scatterplot3d')
library(scatterplot3d)

 

2) 3-D plot

- 3D scatterplot : scatterplot(데이터$변수, pch= , ...)

data(trees)  scatterplot3d 안에 있는 데이터

par(mfrow = c(1, 1))
s3d <- scatterplot3d(trees, type="h", highlight.3d=TRUE, angle=55, scale.y=0.7, pch=16, main="scatterplot3d - 5")

 

- 데이터 trees에 관하여 : help(trees), head(trees), write.csv(....)

help(trees)
head(trees)

write.csv(trees,file="trees.csv", row.names = FALSE)

trees 데이터

Girth : 체리나무의 지름 (inch)

Height : 체리나무의 키 (feet)

Volume : 나무의 부피(ft^3)

=> 나무의 둘레(x1)와 키(x2)로 목재의 부피(y)를 예측

=> y=f(x1, x2)

 

- 데이터 내보내기 (실습)

 

- 3D 산점도에 선형식 추가

data(trees)

par(mfrow = c(1, 1))
s3d <- scatterplot3d(trees, type="h", highlight.3d=TRUE, angle=55, scale.y=0.7, pch=16, main="scatterplot3d - 5")

산점도를 s3d(이름은 자유로 지정)로 저장하고,

 

attach(trees)
my.lm <- lm(Volume ~ Girth + Height) 

s3d의 요소중 planed3d에 lm(Volume~Girth+Height)의 선형식을 추가
s3d$plane3d(my.lm, lty.box = "solid")

lm(linear model)

lm(y변수~x변수+x변수+..)

여기서는 y변수(나무의 부피), x변수(나무의 지름, 키)

=> 나무의 부피는 나무의 지름이 클수록, 나무의 키가 클수록 크다

 

3) 히트맵 (heatmap)

- 히트맵 : 통계치를 구한후 크기에 비례하여 그라데이션 색상으로 표현한 시각화기법. 색상을 열의 온도를 연상하게 해서 열(heatmap)이라고 함

Autompg 데이터의 상관계수를 이용한 히트맵

car<-read.csv("autompg.csv")
attach(car)

par(mfrow=c(1, 1))
cor.x<-cor(car[,1:6])

 

round(cor.x,2)  상관행렬의 시각화 : 대각선에 위치한 변수들이 상관계수가 가장 큰것을 알수 있음


heatmap(cor.x, symm=TRUE)

 

- 데이터 : USArrest (미국범죄율 데이터, 1973)

help(USArrests)
head(USArrests)

cor(USArrests)
round(cor(USArrests), 2)  상관계수(변수간 상관관계)

 

- 미국 (1973, State별 범죄)

x  <- as.matrix(USArrests[, -3])      4개의 변수들 중 UrbanPop(도심인구비율) 변수는 제외한 행렬
result <- heatmap(x, scale="column", Colv=NA, cexCol=1,
                  main="Violent Crime Rates by US State (1973)")

인구 십만명당 폭행, 살인, 성범죄 비율에 따른 히트맵 : 범죄비율이 높은 주부터 낮은 주를 표시

(빨간색이 범죄율 낮은 주)

 

row.names(USArrests)[result$rowInd[1:10]]

범죄발생 낮은주(10개주 1:10)
row.names(USArrests)[result$rowInd[35:50]]

범죄발생 높은주(16개주 35:50)