'모자이크 그림'에 해당되는 글 1건

  1. 2015.08.22 R 모자이크 그림: vcd패키지 mosaic() 함수 2

변수의 개수 및 데이터의 형태에 따라서 그래프, 시각화 방법이 달라지는데요,

 

지난번 포스팅에서는 연속형 데이터의 시각화 방법으로

 - 히스토그램(Histogram)
    : geom_histogram()

- 커널 밀도 곡선(Kernel Density Curve)
    : geom_density()

 - 박스 그래프(Box Plot)
    : geom_boxplot()

 - 바이올린 그래프(Violin Plot)
    : geom_violin()

에 대해서 알아보았습니다. 

 

 

이번 포스팅에서는 범주형 데이터의 시각화 방법으로서

 

 - 막대그림(Bar Chart): geom_bar()

 - 원그림(Pie Chart): geom_bar() + coord_polar()

 - 모자이크 그림(Mosaic Chart): vcd 패키지 mosaic()

 

에 대해서 소개해드리겠습니다.

 

 

[ 변수 개수 및 데이터 형태에 따른 그래프 ]

  

 

모자이크 그림(Mosaic Chart)은 Marimekko chart, Eikosogram 이라고도 하는데요, 특히 2개 이상의 다변량 변수를 한꺼번에 그림으로 나타내어 탐색적 분석을 할 때 아주 유용합니다. 

 

모자이크 그림은 vcd 패키지의 mosaic() 함수를 이용하겠으며, 데이터는 MASS 패키지의 cars93 데이터 프레임 내에 있는 차종(Type), 제조국(Origin), DriveTrain(Rear, Front, 4WD) 의 3개 변수를 모자이크 그림으로 표현해 보겠습니다.

 

> library(MASS)

> str(Cars93)
'data.frame':	93 obs. of  27 variables:
 $ Manufacturer      : Factor w/ 32 levels "Acura","Audi",..: 1 1 2 2 3 4 4 4 4 5 ...
 $ Model             : Factor w/ 93 levels "100","190E","240",..: 49 56 9 1 6 24 54 74 73 35 ...
 $ Type              : Factor w/ 6 levels "Compact","Large",..: 4 3 1 3 3 3 2 2 3 2 ...
 $ Min.Price         : num  12.9 29.2 25.9 30.8 23.7 14.2 19.9 22.6 26.3 33 ...
 $ Price             : num  15.9 33.9 29.1 37.7 30 15.7 20.8 23.7 26.3 34.7 ...
 $ Max.Price         : num  18.8 38.7 32.3 44.6 36.2 17.3 21.7 24.9 26.3 36.3 ...
 $ MPG.city          : int  25 18 20 19 22 22 19 16 19 16 ...
 $ MPG.highway       : int  31 25 26 26 30 31 28 25 27 25 ...
 $ AirBags           : Factor w/ 3 levels "Driver & Passenger",..: 3 1 2 1 2 2 2 2 2 2 ...
 $ DriveTrain        : Factor w/ 3 levels "4WD","Front",..: 2 2 2 2 3 2 2 3 2 2 ...
 $ Cylinders         : Factor w/ 6 levels "3","4","5","6",..: 2 4 4 4 2 2 4 4 4 5 ...
 $ EngineSize        : num  1.8 3.2 2.8 2.8 3.5 2.2 3.8 5.7 3.8 4.9 ...
 $ Horsepower        : int  140 200 172 172 208 110 170 180 170 200 ...
 $ RPM               : int  6300 5500 5500 5500 5700 5200 4800 4000 4800 4100 ...
 $ Rev.per.mile      : int  2890 2335 2280 2535 2545 2565 1570 1320 1690 1510 ...
 $ Man.trans.avail   : Factor w/ 2 levels "No","Yes": 2 2 2 2 2 1 1 1 1 1 ...
 $ Fuel.tank.capacity: num  13.2 18 16.9 21.1 21.1 16.4 18 23 18.8 18 ...
 $ Passengers        : int  5 5 5 6 4 6 6 6 5 6 ...
 $ Length            : int  177 195 180 193 186 189 200 216 198 206 ...
 $ Wheelbase         : int  102 115 102 106 109 105 111 116 108 114 ...
 $ Width             : int  68 71 67 70 69 69 74 78 73 73 ...
 $ Turn.circle       : int  37 38 37 37 39 41 42 45 41 43 ...
 $ Rear.seat.room    : num  26.5 30 28 31 27 28 30.5 30.5 26.5 35 ...
 $ Luggage.room      : int  11 15 14 17 13 16 17 21 14 18 ...
 $ Weight            : int  2705 3560 3375 3405 3640 2880 3470 4105 3495 3620 ...
 $ Origin            : Factor w/ 2 levels "USA","non-USA": 2 2 2 2 2 1 1 1 1 1 ...
 $ Make              : Factor w/ 93 levels "Acura Integra",..: 1 2 4 3 5 6 7 9 8 10 ... 

 

 

(1) vcd 패키지 설치, 호출 후에 차종(Type)과 제조국(Origin) 2개의 변수를 가지고, 세로 방향(direction="v") 으로 모자이크 그림을 그려보겠습니다.  table() 함수를 써서 분할표를 먼저 만들고, 이걸 가져다가 모자이크 그림을 그리게 됩니다.

 

> # vcd package installation > install.packages("vcd") > library(vcd) > > # 모자이크 그림 : 차종(Type) & 제조국(Origin) > # 세로 방향 > table_1 <- with(Cars93, table(Type, Origin)) >

> table_1
         Origin
Type      USA non-USA
  Compact   7       9
  Large    11       0
  Midsize  10      12
  Small     7      14
  Sporty    8       6
  Van       5       4

 

 

>

> mosaic(table_1, + gp=gpar(fill=c("yellow", "blue")), + direction="v", # 세로 + main="Mosaic Chart by Car Type and Origin, using vcd package")

 

 

 

 

(2) 차종(Type)과 제조국(Origin) 2개의 변수를 가지고, 모자이크 그림을 가로 방향 (direction="h") 으로  그리면 아래와 같습니다.  Origin이 y축에 있던 것이 x축으로 바뀌었습니다.

 

> # 가로 방향
> mosaic(table_1, 
+        gp=gpar(fill=c("yellow", "blue")), 
+        direction="h", # 가로
+        main="Mosaic Chart by Car Type and Origin, direction=horizontal")

 

 

 

 

 

 

(3) 이번에는 변수를 하나 더 추가해서 차종(Type), 제조국(Origin), DriveTrain 의 3개의 변수를 가지고 모자이크 그림을 그려보겠습니다.  먼저 table()함수를 써서 3개 변수에 대한 분할표를 만들고, 이를 가져다가 모자이크 그림을 그리게 됩니다.

 

> # 모자이크 그림 : 차종(Type) & 제조국(Origin) & DriveTrain(Rear, Front, 4WD)
> # 세로 방향
> 

> # 3개 변수별 범주 확인

> levels(Cars93$Type)
[1] "Compact" "Large"   "Midsize" "Small"   "Sporty"  "Van"    
> levels(Cars93$Origin)
[1] "USA"     "non-USA"
> levels(Cars93$DriveTrain)
[1] "4WD"   "Front" "Rear"
> table_2 <- with(Cars93, table(Type, Origin, DriveTrain))
> 
> table_2
, , DriveTrain = 4WD

         Origin
Type      USA non-USA
  Compact   0       1
  Large     0       0
  Midsize   0       0
  Small     0       2
  Sporty    2       0
  Van       3       2

, , DriveTrain = Front

         Origin
Type      USA non-USA
  Compact   7       6
  Large     7       0
  Midsize   9       8
  Small     7      12
  Sporty    2       5
  Van       2       2

, , DriveTrain = Rear

         Origin
Type      USA non-USA
  Compact   0       2
  Large     4       0
  Midsize   1       4
  Small     0       0
  Sporty    4       1
  Van       0       0

> 
> 
> mosaic(table_2, 
+        gp=gpar(fill=c("yellow", "blue", "red")), 
+        direction="v", 
+        main="Mosaic Chart by Car Type, Origin and DriveTrain, direction=v")

 

 

 

 

 

 

마지막으로, 모자이크 그림에 비율 라벨(Mosaic Chart with Percentage Label)을 추가해보겠습니다.

 

> # 비율 라벨 추가 (Mosaic Chart with Percentage Labels)
> table_1 <- with(Cars93, table(Type, Origin))
> proportions <- round(prop.table(table_1)*100, 1) # 백분율, 소수점 첫째자리 반올림
> 
> proportions
         Origin
Type       USA non-USA
  Compact  7.5     9.7
  Large   11.8     0.0
  Midsize 10.8    12.9
  Small    7.5    15.1
  Sporty   8.6     6.5
  Van      5.4     4.3
> 
> values <- c(table_1)
> rowvarcat <- c("USA","non_USA")
> columnvarcat <- c("Compact","Large", "Midsize", "Small", "Sporty", "Van")
> names=c("Origin", "Type")
> dims <- c(2,6)
> 
> TABS <- structure( c(values), 
+                    .Dim = as.integer(dims), 
+                    .Dimnames = structure( list(rowvarcat, columnvarcat ),
+                    .Names = c(names) ) , class = "table") 
> 
> PROPORTIONS <- structure( c(proportions), 
+                           .Dim = as.integer(dims), 
+                           .Dimnames = structure( list(rowvarcat,columnvarcat ),
+                           .Names = c(names) ) , class = "table") 
> 
> TABSPROPORTIONS <- structure( c(paste(proportions,"%","\n", "(",values,")",sep="")), 
+                               .Dim = as.integer(dims), 
+                               .Dimnames = structure( list(rowvarcat,columnvarcat ),
+                               .Names = c(names) ) , class = "table") 
> 
> mosaic(TABS, 
+        pop=FALSE, 
+        main="Mosaic Chart by Car Type and Origin, with Percentage Labels")
> 
> labeling_cells(text=TABSPROPORTIONS, clip_cells=FALSE)(TABS)

 

 

 

* Michael Friendly’s book “Visualizing Categorical Data” 예제 참고 

 

많은 도움 되었기를 바랍니다.

 

이번 포스팅이 도움이 되었다면 아래의 '공감 ~♡' 단추를 꾸욱 눌러주세요.^^

 

728x90
반응형
Posted by Rfriend
,