Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

초보자의 빅데이터 정복기

22-08-08 chap05_DataVisualization 본문

아이티월 수업일지(R)

22-08-08 chap05_DataVisualization

서부남93 2022. 8. 9. 10:57

chap05_DataVisualization

# 1. 이산형 변수 시각화 

# 차트 데이터 생성
chart_data <- c(305,450, 320, 460, 330, 480, 380, 520) 

#벡터 원소에 이름 적용 
names(chart_data) <- c("2016 1분기","2017 1분기","2016 2분기","2017 2분기","2016 3분기","2017 3분기","2016 4분기","2017 4분기")

length(chart_data)
length(names(chart_data))
# 1) 막대차트 
help(barplot)

# [1] 세로막대차트 
barplot(chart_data, ylim = c(0, 600),
        col = rainbow(8), 
        ylab = '매출액(단위:천원)', 
        xlab = "년도별 분기현황",
        main ="2016년 vs 2017년 분기별 매출현황")

# [2] 가로막대차트 : horiz = TRUE
barplot(chart_data, xlim = c(0, 600),
        horiz = TRUE, 
        col = rainbow(8), 
        ylab = '년도별 분기현황', 
        xlab = "매출액(단위:천원)",
        main ="2016년 vs 2017년 분기별 매출현황")


# [3] 1행 2열 차트 그리기
par(mfrow=c(1,2)) # 1행 2열 그래프 보기

# 1940년 버지니아의 1000명당 사망률
VADeaths 
str(VADeaths)
# 왼쪽 : 개별막대 
barplot(VADeaths, beside=T, col=rainbow(5),
        main="미국 버지니아주 하위계층 사망비율")
# 범례추가 
legend(19, 71, c("50-54","55-59","60-64","65-69","70-74"), 
       cex=0.8,  fill=rainbow(5))
#legend(x,y,범례레이블, cex = 확대/축소, fill = 범례 색상)

# 오른쪽 : 누적형 막대 
barplot(VADeaths, beside=F,col=rainbow(5),
        main="미국 버지니아주 하위계층 사망비율")

# [text] 추가
par(mfrow=c(1,1)) # 1행 2열 그래프 보기

bp<- barplot(chart_data, ylim = c(0, 600),
        col = rainbow(8), 
        ylab = '매출액(단위:천원)', 
        xlab = "년도별 분기현황",
        main ="2016년 vs 2017년 분기별 매출현황")

# text 반영 
text(x =bp , y= chart_data +20,labels = chart_data,cex = 0.7, col = 'black')
#x,y : text 위치, labels: text, col: text 색상

#[범례 추가]
barplot(chart_data, ylim = c(0, 600),
        col = rainbow(8), 
        ylab = '매출액(단위:천원)', 
        xlab = "년도별 분기현황",
        main ="2016년 vs 2017년 분기별 매출현황",
        legend.text = names(chart_data),
        args.legend = list(x='topleft'))

# left, 'topleft', 'top','topright'


# 2) 점 차트 
par(mfrow=c(1,1)) # 1행 1열 차트 그리기

dotchart(chart_data, color=c("green","red"), lcolor="black",
         pch=1:2, labels=names(chart_data), xlab="매출액",
         main="분기별 판매현황 점 차트 시각화", cex=1.2)


# 3) 파이 차트 
pie(chart_data, labels = names(chart_data), 
    border = 'blue', col = rainbow(8), cex=1.2)

# 차트 제목 추가 
title("분기별 판매현황", cex.main = 2)

#비율 (점유율) 시각화에 유용 : 중복 응답 반영(x)

genre <- c(45,25,15,30) #100명
sum(genre)

names(genre) <-c('액션','스릴러','공포','드라마')
genre

pie(genre,labels = names(genre),col = rainbow(4))

#액션 = 45/115

#비율 계산
rate <- round(genre / sum(genre)*100,2)
rate #39.13  21.74  13.04  26.09 

labels <- names(genre)
labels

#paste(): 문자열 결합
labels_text <- paste(labels,'\n',rate)

#labels + 줄바꿈 +비율
pie(genre,labels = labels_text,col = rainbow(4))

#막대차트  중복응답 반영(o)
barplot(genre ,col = rainbow(4), ylim = c(0,50))




# 2. 연속형 변수 시각화 
# -연속된 값을 갖는 변수(시간, 길이, 키 ,몸무게등)

# 1) 상자그래프 
VADeaths # 1940년 버지니아의 1000명당 사망률
# 연령 그룹, 인구 그룹[시골 남,여, 도시 남,여] 

#요약통계량
summary(VADeaths)# 최솟값/최댓값, 사분위수, 평균 , 이상치 

boxplot(VADeaths) # 상자그래프 :최솟값/최댓값, 사분위수, 사분위수 , 이상치 
#사분위수: 1사분, 2사분(중위수), 3사분

# 사분위수 제공
quantile(iris$Sepal.Length)
#0%  25%  50%  75% 100% 
#4.3  5.1  5.8  6.4  7.9 
#min  q1    q2   q3  max 

# 행과 열의 이름 추출
row.names(VADeaths)
colnames(VADeaths)


# 2) 히스토그램 : 각 계급의 빈도수 
str(iris) # 붗꽃 
#'data.frame': 150 obs. of  5 variables:
#$ Sepal.Length: 꽃받침 길이 num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
#$ Sepal.Width : 꽃받침 넓이 num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
#$ Petal.Length: 꽃잎 길이 num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
#$ Petal.Width : 꽃잎 넓이 num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
#$ Species     : 꽃잎 종 Factor w/ 3 levels "setosa","versicolor"


# [1] 일반 히스토그램 
hist(iris$Sepal.Length, xlab = '꽃받침 길이', main = '붗꽃 꽃받침 길이')
range(iris$Sepal.Length)

# [2] 계급수 조정 : breaks
hist(iris$Sepal.Length, xlab = '꽃받침 길이',
     breaks = 30,
     main = '붗꽃 꽃받침 길이')

# [3] 확률밀도 함수(PDF): 확률변수 X의 크기를 추정하는함수
# step1 :확률 밀도로 히스토그램 그리기 - 연속형변수의 확률
hist(iris$Sepal.Width, xlab="iris$Sepal.Width",
     col="mistyrose",freq = F,
     main="iris 꽃받침 넓이 histogram", xlim=c(2.0, 4.5))
# step2:확률밀도분포곡선: 밀도를 기준으로 line을 그려준다.
lines(density(iris$Sepal.Width), col="red")

# step3: 정규분포 곡선: dnorm(): 정규분포 추정 -> 곡선
range(iris$Sepal.Width)

x <- seq(2.0, 4.5, 0.1)
curve(dnorm(x, mean=mean(iris$Sepal.Width), sd=sd(iris$Sepal.Width)),
      col="blue", add = T)




  # 3) 산점도 
#plot(x,y,....)
plot(x = iris$Sepal.Length, y= iris$Petal.Length) #plot(x, y)
plot(iris$Petal.Length ~ iris$Sepal.Length) #plot(y, x)
plot(x = iris$Sepal.Length, y= iris$Petal.Length,
     col = iris$Species) #plot(x,y,col)
#col : 범주형 변수 이용

price <- runif(100, min = 1, max = 100) # 1~100 난수 100개
plot(price) #plot(y), x: 타입(index)

par(mfrow=c(2,2)) # 2행 2열 차트 그리기
# plot() 함수 속성 : pch : 연결점 문자타입-> plotting characher-번호(1~30)
plot(price, type="o", pch=5) # 빈 사각형
plot(price, type="o", pch=15)# 채워진 마름모
plot(price, type="o", pch=20, col="blue") #color 지정
plot(price, type="o", pch=20, col="orange", cex=1.5) #character expension(확대)



#만능 차트
methods(plot)

#1) 시계열 data -> 추세선
WWWusage
plot(WWWusage)

# 2) 선형회귀모델 -> 관련 차트
model <- lm(formula = iris$Petal.Length ~ iris$Sepal.Length)

plot(model)

#plot 2개 겹치기
plot(iris$Sepal.Length, type = 'o', ann=FALSE, col='blue')
par(new = T) #그래프 겹치기

#추가 plot
plot(iris$Petal.Length, type= 'o',axes=FALSE ,col='red')
#축눈금 제외 : axes

#범례 추기
legend(x=0,y=7,legend = c('꽃받침의 길이','꽃잎의 길이'),
       col =c('blue','red'),lty = 1)

# 4) 산점도 행렬(scatter matrix) : 변수 비교 
dim(iris)# 150   5

pairs(iris[,1:4])

# 꽃의 종별 산점도 
pairs(iris[iris$Species=="setosa",1:4]) # [조건식,숫자색인]
pairs(iris[iris$Species=="versicolor",1:4])
pairs(iris[iris$Species=="virginica",1:4])


#3차원 데이터셋 이용
str(iris3)
# num [1:50, 1:4, 1:3] -> [행,열,면] 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
# - attr(*, "dimnames")=List of 3
# ..$ : NULL -> 이름 없음
# ..$ : chr [1:4] "Sepal L." "Sepal W." "Petal L." "Petal W." : 열 이름
# ..$ : chr [1:3] "Setosa" "Versicolor" "Virginica": 면 이름

#문자색인 
iris3[,c("Sepal L.","Petal L."),"Setosa"]
iris3[,c("Sepal L.","Petal L."),c("Setosa","Virginica")]
#iris3[,c("Sepal L.":,"Petal L."),c("Setosa","Virginica")]# 문자색인 콜론(x)
iris3[,1:3,c("Setosa","Virginica")]# 숫자색인 콜론(o)

 
# 5) 차트 파일 저장 
setwd("C:/ITWILL/3_Rwork/output")

jpeg("iris.jpg", width = 720, height = 480) # open
pairs(iris[,1:4]) # 차트 
dev.off() # close


### 3차원 산점도 
#- 주성분 분석 또는 요인분석에서 이용

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

# 꽃의 종류별 자료준비 
iris_setosa = iris[iris$Species == 'setosa',]
iris_versicolor = iris[iris$Species == 'versicolor',]
iris_virginica = iris[iris$Species == 'virginica',]

dim(iris_setosa) #[1] 50  5


# scatterplot3d(x = 밑변, z = 오른쪽변, y = 왼쪽변, type='n') # type='n' : 기본 산점도 제외 
d3 <- scatterplot3d(iris$Petal.Length, iris$Sepal.Length, iris$Sepal.Width, type='n')

range(iris$Petal.Length) #1.0 6.9

# 꽃의 종별 분포도
#setosa
d3$points3d(iris_setosa$Petal.Length, iris_setosa$Sepal.Length,
            iris_setosa$Sepal.Width, bg='orange', pch=21)

#versicolor
d3$points3d(iris_versicolor$Petal.Length, iris_versicolor$Sepal.Length,
            iris_versicolor$Sepal.Width, bg='blue', pch=23)

#virginica
d3$points3d(iris_virginica$Petal.Length, iris_virginica$Sepal.Length,
            iris_virginica$Sepal.Width, bg='green', pch=25)


'아이티월 수업일지(R)' 카테고리의 다른 글

22-08-09 chap06_2_EDA_Preprocessing  (0) 2022.08.10
22-08-09 chap06_1_Datahandling  (0) 2022.08.09
22-08-08 chap04_2_Function  (0) 2022.08.08
22-08-05 chap04_1_Control  (0) 2022.08.05
22-08-04 chap3_DataIO_String  (0) 2022.08.05
Comments