본문 바로가기

■ 프로그래밍/R

[R 기초] 일변량 질적자료의 표, 막대그래프, 원그래프

[ R : 일변량 질적자료의 표, 막대그래프, 원그래프 ]


패키지 설치 및 로딩하기

install.packages("ggplot2")
library(ggplot2)


데이터 불러오기

ggplot2::diamonds # 패키지명::데이터or함수
## # A tibble: 53,940 x 10
##    carat cut       color clarity depth table price     x     y     z
##    <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
##  1 0.23  Ideal     E     SI2      61.5    55   326  3.95  3.98  2.43
##  2 0.21  Premium   E     SI1      59.8    61   326  3.89  3.84  2.31
##  3 0.23  Good      E     VS1      56.9    65   327  4.05  4.07  2.31
##  4 0.290 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63
##  5 0.31  Good      J     SI2      63.3    58   335  4.34  4.35  2.75
##  6 0.24  Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48
##  7 0.24  Very Good I     VVS1     62.3    57   336  3.95  3.98  2.47
##  8 0.26  Very Good H     SI1      61.9    55   337  4.07  4.11  2.53
##  9 0.22  Fair      E     VS2      65.1    61   337  3.87  3.78  2.49
## 10 0.23  Very Good H     VS1      59.4    61   338  4     4.05  2.39
## # ... with 53,930 more rows

diamonds는 ggplot2 package에 내장되어 있는 기본 데이터이다.
패키지명을 꼭 쓸 필요는 없다.
하지만 패키지를 많이 설치하다보면 함수명이 겹치는 경우가 있어 구분지어 주는 습관을 기르는 것이 좋다.


데이터 자료 보기
1. 질적 자료: 글자, (의미없는)숫자
1) 명목형 자료: ex. 종교
2) 순서형 자료: ex. 만족도, 학년 (서로 더해도 의미가 없음)
2. 양적 자료: 숫자 : ex. 온도, 나이, 가격


[diamonds 데이터]
- 질적 자료: cut, color, clarity
- 양적 자료: carat, depth, table, price, x, y, z


일변량(Uni-variate): 질적 자료의 분석

1. 표 = 빈도표(Frequency Table)

(1) 빈도(Frequency)

  • table(data$variable) : 해당된 데이터 자료의 개수 = 빈도
table(diamonds$cut)
## 
##      Fair      Good Very Good   Premium     Ideal 
##      1610      4906     12082     13791     21551


- 실전에서는 가장 많은 것부터 차례대로 = 내림차순

sort(table(diamonds$cut) , decreasing = TRUE )
## 
##     Ideal   Premium Very Good      Good      Fair 
##     21551     13791     12082      4906      1610


- for문(반복문)을 이용한 빈도 내림차순 정리

for(i in 2:4){
  print(sort(table(diamonds[ , i]) , decreasing = TRUE))
}
## 
##     Ideal   Premium Very Good      Good      Fair 
##     21551     13791     12082      4906      1610 
## 
##     G     E     F     H     D     I     J 
## 11292  9797  9542  8304  6775  5422  2808 
## 
##   SI1   VS2   SI2   VS1  VVS2  VVS1    IF    I1 
## 13065 12258  9194  8171  5066  3655  1790   741


(2) 백분율(Percent) = (빈도/합계) * 100(%)

  • prop.table(frequency)*100
prop.table(table(diamonds$cut)) *100
## 
##      Fair      Good Very Good   Premium     Ideal 
##  2.984798  9.095291 22.398962 25.567297 39.953652
  • 비율은 0-1
sort(prop.table(table(diamonds$cut)) *100 , decreasing = TRUE )
## 
##     Ideal   Premium Very Good      Good      Fair 
## 39.953652 25.567297 22.398962  9.095291  2.984798
  • 백분율은 관례로 소수점을 하나까지만 표현 = round( , digit = )
round(sort(prop.table(table(diamonds$cut)) *100 , decreasing = TRUE ), digits = 1)
## 
##     Ideal   Premium Very Good      Good      Fair 
##      40.0      25.6      22.4       9.1       3.0


문제1. 각 질적 자료에 대해서 빈도와 백분율을 구하라. (for문 이용)


2. 그래프(Graph)

(1) 막대그래프(Bar Chart)

  • barplot(frequency or percent)
barplot(sort(table(diamonds$cut),  # 데이터
        decreasing = TRUE),        # 내림차순 정렬
        col = "lightblue",         # 색상
        main = "Cut of Diamonds")  # 차트 제목


  • 차트 색상은 막대별로 지정 가능
    ex. col = c(“aquamarine”, “pink”, “red”, “tan1”, “black”))

  • 패키지 이용 그라데이션으로 바꾸기

color.palatte <- RColorBrewer::brewer.pal(n = 5, name = "BuGn")
barplot(sort(table(diamonds$cut), 
        decreasing = TRUE), 
        col = color.palatte)


R color cheatsheet : https://www.nceas.ucsb.edu/~frazier/RSpatialGuides/colorPaletteCheatsheet.pdf


  • y축
barplot(sort(table(diamonds$cut), 
        decreasing = TRUE), 
        col  = "lightblue",
        main = "Cut of Diamonds",
        ylab = "Frequency",  # y축 제목
        ylim = c(0, 25000))  # y축 범위 : ylin = c(min, max)


  • 가로 막대그래프
barplot(sort(table(diamonds$cut), 
        decreasing = FALSE), 
        col   = "lightblue",
        main  = "Cut of Diamonds",
        xlab  = "Frequency",
        xlim  = c(0, 25000),
        horiz = TRUE)


문제2. 3개의 질적 자료에 대한 가로 막대 그래프 작성. (for문 이용)


i. 그래프 제목을 해당 변수에 맞게 바꾸기

paste("Love", "is", "choice.")
## [1] "Love is choice."

결과는 character 형식으로 보여주며, dafault로 문자 사이에 space 존재

paste(colnames(diamonds)[2:4], "of Diamonds")
## [1] "cut of Diamonds"     "color of Diamonds"   "clarity of Diamonds"


문제3. paste를 이용하여 Var1, Var2, … , Var100 작성하기.


ii. 그래프 화면 분할하기
- 기본적으로 하나의 그래픽 화면에 하나의 그래프만 출력
- par(mfrow = c(nrow, ncol)) : 행부터 그래프를 채움
- par(mfcol = c(nrow, ncol)) : 열부터 그래프를 채움

par(mfrow = c(1, 3))

for(i in 2:4){
  barplot(sort(table(diamonds[ , i]) , decreasing = FALSE), 
          col   = "lightblue",
          main  = paste(colnames(diamonds)[i], "of Diamonds"),
          ylab  = "Frequency",
          ylim  = c(0, 25000))
}


- 그래프 화면 원상태로 돌리기 : par(mfrow = c(1,1))


(2) 원그래프(Pie Chart)

  • pie(frequency or percent)
pie(sort(table(diamonds$cut), 
    decreasing = TRUE),
    radius = 1) # 반지름, dafault 는 0.8


i. 시계방향 : Clockwise = TRUE
- 첫 번째 조각의 시작 각도 init.angle
- init.angel의 default : 시계방향은 90(북쪽), 반시계방향은 0(동쪽)

pie(sort(table(diamonds$cut) , decreasing = TRUE),
    radius = 1,
    clockwise = TRUE,
    init.angle = 0)


문제4. 그래픽 화면을 3행 2열로 분할하고, 각 행에 각 질적 자료의 막대그래프, 원그래프 출력.


pdf 파일에 그래프 저장하기
- pdf(file = “directory/filename.pdf”) : 저장 시작
- 그래프 작업
- dev.off() : 저장 끝
- dev : graphic device의 약자

pdf(file = "graphics.pdf")

par(mfrow = c(3, 2)) # 한 페이지에 여러 그래프 저장하려고 분할하기

for(i in 2:4){
  barplot(sort(table(diamonds[ , i]) , decreasing = TRUE), 
          col   = "aquamarine",
          main  = paste(colnames(diamonds)[i], "of Diamonds"),
          ylab  = "Frequency",
          ylim  = c(0, 25000))
  
  pie(sort(table(diamonds[ ,i]) , decreasing = TRUE),
      radius = 1,
      clockwise = TRUE,
      init.angle = 0,
      main  = paste(colnames(diamonds)[i], "of Diamonds"))
}

dev.off()



[정답]
문제 1.

for(i in c("cut", "color", "clarity")){
  print(sort(table(diamonds[ , i]), 
             decreasing = TRUE))
  
  print(round(sort(prop.table(table(diamonds[ , i]))*100 , decreasing = TRUE ), digits = 1))
}

문제 2.

for(i in 2:4){
  barplot(sort(table(diamonds[ , i]), 
          decreasing = FALSE), 
          col   = "aquamarine",
          main  = "Cut of Diamonds",
          xlab  = "Frequency",
          xlim  = c(0, 25000),
          horiz = TRUE)
}

문제 3.

paste("Var", 1:100, sep = "")

문제 4.

par(mfrow = c(3, 2))

for(i in 2:4){
  barplot(sort(table(diamonds[ , i]) , decreasing = TRUE), 
          col   = "lightblue",
          main  = paste(colnames(diamonds)[i], "of Diamonds"),
          ylab  = "Frequency",
          ylim  = c(0, 25000))
  
  pie(sort(table(diamonds[ ,i]) , decreasing = TRUE),
      radius = 1,
      clockwise = TRUE,
      init.angle = 0,
      main  = paste(colnames(diamonds)[i], "of Diamonds"))
}