지난번 포스팅에서는 그래프에 추가적인 정보를 입력하는 낮은 수준의 그래프 함수(low level graphic functions) 중에서

(1) 제목, XY축 Label 추가하는 title()

(2) XY축의 형태를 변환하는 axis(side, ...)

(3) 직선 연결, 추가 : lines(x, y), abline(a, b), abline(h=y), abline(v=x)

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

 


이번 포스팅에서는 낮은 수준의 그래프 함수 네번째로 (4) 점 추가 : points(x, y) 에 대해서 소개하겠습니다.



[ 낮은 수준의 그래프 함수 (Low level graphic function) ]

 

 

 

points() 함수의 일반적인 사용법은 다음과 같습니다.

 

points(x, y = NULL, type = "p", ...) 

 

 구분

기능 설명 

 x, y

 x, y 좌표 벡터

 (coordinate vectors of points to plot) 

 type = "p"

 그래프 유형 = "점 그래프" 

 ...

 기호 모양(pch), 색깔(col), 크기(cex) 등의 그래프 모수 (parameters) 사용

 

 

 

MASS 패키지에 내장되어 있는 Cars93 데이터프레임의 차량 무게(Weight), 고속도로 연비 (MPG.highway), 차종 (Type) 변수를 사용해서 점을 추가하는 그래프를 실습해보겠습니다.

 

높은 수준의 그래프 함수 중에서 plot(x, y, type = 'p') 로 하면 점 그래프 (points plot)을 그릴 수 있습니다.  아래에 plot(x, y, type = 'p')로 그린 산점도와 points(x, y) 함수로 점을 추가한 그래프 예시를 들어보았습니다.  정확히 두 개 그래프가 일치합니다. 

 

> ##-----------------------------------------
> ## adding points() : point(x, y)
> ##-----------------------------------------
> 
> # to use Cars93 dataframe
> 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 ...
> 
> # scatter plot
> attach(Cars93)
> 
> plot(Weight, MPG.highway, type = 'p') # points plot

 

 

 

> # adding points to the current plot > plot(Weight, MPG.highway, type = 'n') # blank plot > points(Weight, MPG.highway) # exactly the same with the upper points plot

 

 

 

 

 

그러면 왜 굳이 points() 라는 낮은 수준의 함수를 가지고 점을 추가하려고 하는 것인지 의문이 들것입니다. 그 이유는 points() 함수를 가지고 필요에 따라서 순차적으로 점을 추가할 수 있고, 조건을 부여하고 그래프 모수 중에 색깔이나 기호 모양 등을 다르게 해서 탐색적 분석을 진행하는데 유용하기 때문입니다.  물론 plot(x, y, type = 'p')로 원하는 그래프를 그릴 수 있다면 points() 함수를 사용할 필요는 없겠지요.  아래에 points()의 몇 가지 사용 형태를 보시고 필요한 상황에 맞게 골라 쓰면 되겠습니다.

 

아래에는 차종(Type)별로 기호 모양과 색깔을 달리하면서 무게(Weight)와 고속도로 연비(MPG.highway) 산포도를 그려보겠습니다.  2차원의 x, y 공간에 차종(Type)이라는 제3의 차원을 추가해서 볼 수 있는 매우 유용한 방법입니다. 대신 Base Graphics 에서는 조건의 갯수만큼 손이 참 많이 가는 단점이 있습니다 (참고로, ggplot2 plotting system을 사용하면 조건에 따른 색이나 기호를 달리하도록 지정하는게 한 줄이면 끝나고, 범례(legend)도 알아서 추가해주므로 편합니다)

 

 

> # adding points to the current plot with pch, col, cex parameters
> plot(Weight, MPG.highway, type = 'n') # blank plot
> points(Weight, MPG.highway, pch = 15, col = "blue", cex = 1.5)
 

 

 

 

 

> # adding points with different characters by condition
> plot(Weight, MPG.highway, type = 'n') # blank plot
> 
 

 


> table(Cars93$Type)

Compact   Large Midsize   Small  Sporty     Van 
     16      11      22      21      14       9 
> 
> # Type = Compact
> points(Weight[Type == "Compact"], MPG.highway[Type == "Compact"], pch = 0)
> 

 


> # Type = Large
> points(Weight[Type == "Large"], MPG.highway[Type == "Large"], pch = 1)
> 

 


> # Type = Midsize
> points(Weight[Type == "Midsize"], MPG.highway[Type == "Midsize"], pch = 17, col = "yellow")
> 

 


> # Type = Small
> points(Weight[Type == "Small"], MPG.highway[Type == "Small"], pch = 3)
> 

 

 

> # Type = Sporty
> points(Weight[Type == "Sporty"], MPG.highway[Type == "Sporty"], pch = 9)
> 

 


> # Type = Van
> points(Weight[Type == "Van"], MPG.highway[Type == "Van"], pch = 15, col = "blue")
> 
> title("adding points with different characters by Car Types")
> 

 

 

 


> 
> # adding legend to topright side
> legend("topright", 
+        c("Compact", "Large", "Midsize", "Small", "Sporty", "Van"), 
+        col = c("black", "black", "yellow", "black", "black", "blue"), 
+        pch = c(0, 1, 17, 3, 9, 15)
+        )
> 

 

 


> detach(Cars93) 

 

 

다음번 포스팅에서는 text(), mtext() 함수로 문자(text)를 추가하는 방법에 대해서 알아보겠습니다.

 

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

 

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

 

728x90
반응형
Posted by Rfriend
,

지난번 포스팅에서는 그래프에 추가적인 정보를 입력하는 낮은 수준의 그래프 함수(low level graphic functions) 중에서 (1) 제목, XY축 Label 추가하는 title(), (2) XY축의 형태를 변환하는 axis(side, ...)에 대해서 알아보았습니다.


이번 포스팅에서는 낮은 수준의 그래프 함수 두번째로 (3) 직선 연결, 추가 : lines(x, y), abline(a, b), abline(h=y), abline(v=x) 에 대해서 소개하겠습니다.



[ 낮은 수준의 그래프 함수 (Low level graphic function) ]

 

 

 

MASS 패키지에 들어있는 Cars93 데이터프레임의 Weight (차의 무게)MPG.highway (고속도로 연비) 두 개의 변수를 가지고 산포도를 그린 후에, lines() 함수로 선형 회귀식을 추가해보고, abline() 함수로 x축과 y축의 평균으로 수직선과 수평선을 추가하여 보겠습니다.

 

 

line()함수의 일반적인 사용법은 다음과 같습니다.

 

lines(x, y = NULL, type = "l", ...)

 

 구분

기능 설명 

 x, y

  x, y 좌표 벡터

 (coordinate vectors of points to join)

 type = "l"

 선(line) 그래프라는 뜻임

 (character indicating the type of plotting)

 ...

 선 유형 (lty), 선 색깔 (col), 선 두께(lwd) 등의 그래프 모수 입력

 (Further graphical parameters)

 

 

 

 

abline() 함수의 사용법은 다음과 같습니다.

 

abline(a = NULL, b = NULL, h = NULL, v = NULL, reg = NULL,
       coef = NULL, untf = FALSE, ...) 

 구분

기능 설명 

a, b 

 절편과 기울기, 단일 값

 (the intercept and slope, single values)

 h

 y값을 지나는 수평인 직선

 (the y-value(s) for horizontal line(s).)

 v

 x값을 지나는 수직인 직선

 (the x-value(s) for vertical line(s).)

 reg

 회귀직선 추가

 (an object with a coef method)

 coef

 절편과 기울기로 이루어진 벡터

 (a vector of length two giving the intercept and slope)

 untf

 변환 안된 값을 쓸지를 묻는 옵션. 만약 y값을 로그변환한 경우 untf = TRUE 라고 설정하면 로그변환 전의 원래값 기준으로 좌표에 그래프가 그려짐

 (logical asking whether to untransform.

If untf is true, and one or both axes are log-transformed, then a curve is drawn corresponding to a line in original coordinates, otherwise a line is drawn in the transformed coordinate system. The h and v parameters always refer to original coordinates)

* 출처 : http://sites.stat.psu.edu/~dhunter/R/html/graphics/html/abline.html

 

 

 

먼저 lm() 함수를 사용해서 y = MPG.highway (고속도로 연비), x = Weight (차의 무게) 변수 간의 선형 회귀모형을 만들면 아래와 같습니다.

 

> ##------------------------------------ > ## adding lines to a plot > ##------------------------------------ > > # fitting regression model > library(MASS) # to use Cars93 dataframe > 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 ... > > # fitting regression model

> fit_1 <- lm(MPG.highway ~ Weight, data = Cars93)
> fit_1

Call:
lm(formula = MPG.highway ~ Weight, data = Cars93)

Coefficients:
(Intercept)       Weight  
  51.601365    -0.007327  

> 
> names(fit_1)
 [1] "coefficients"  "residuals"     "effects"       "rank"          "fitted.values" "assign"       
 [7] "qr"            "df.residual"   "xlevels"       "call"          "terms"         "model" 

 

 

 

 

다음으로, Weight (무게)와 MPG.highway (고속도로 연비)의 두 변수 산포도를 그리고, 위에서 만든 선형 회귀선을 추가해보겠습니다.

 

세가지 방법이 있는데요, (1) lines() 를 사용하는 방법, (2) abline(reg = ) (3) abline(a = coef[1], b = coef[2]) 를 사용하는 방법은 아래와 같습니다.  참고로, 그래프 모수(parameters)로서 색깔 지정은 col, 선 유형 지정은 lty, 선 두께 지정은 lwd 를 사용하면 됩니다.

 

> ## adding regression line to the current plot 
> # (1) lines()
> with(Cars93, plot(MPG.highway ~ Weight)) # scatter plot of MPG.highway~Weight
> lines(Cars93$Weight, fit_1$fitted.values, col = "blue")
> title("adding regression line : lines()")
>

 

 
 
> # (2) abline(reg = regression_model)
> with(Cars93, plot(MPG.highway ~ Weight))
> abline(reg = fit_1, col = "red", lwd = 3)
> title("adding regression line : abline(reg = )")

 

 

 

 

> # (3) abline(a = fit_1$coef[1], b = fit_1$coef[2])
> with(Cars93, plot(MPG.highway ~ Weight))
> abline(a = fit_1$coef[1], b = fit_1$coef[2], col = "black", lwd = 3)
> title("adding regression line : abline(a = coef[1], b = coef[2])")
 

 

> fit_1$coef # coefficients of regression model
 (Intercept)       Weight 
51.601365429 -0.007327059 
> fit_1$coef[1] # intercept
(Intercept) 
   51.60137 
> fit_1$coef[2] # slope
      Weight 
-0.007327059

 

 

 

 

 

이번에는 loess.smooth() 함수로 비모수 회귀곡선을 적합시키고, lines() 함수로 smoothed regression line을 현재 그래프에 추가해보는 방법을 소개하겠습니다.

 

 

> ## adding smoothed regression line to the current plot : lines(), loess.smooth()
> # (1) fitting non-parametric regression model
> fit_2 <- loess.smooth(x = Cars93$Weight, y = Cars93$MPG.highway)
> names(fit_2)
[1] "x" "y"
> fit_2
$x
 [1] 1695.000 1744.184 1793.367 1842.551 1891.735 1940.918 1990.102 2039.286 2088.469 2137.653 2186.837
[12] 2236.020 2285.204 2334.388 2383.571 2432.755 2481.939 2531.122 2580.306 2629.490 2678.673 2727.857
[23] 2777.041 2826.224 2875.408 2924.592 2973.776 3022.959 3072.143 3121.327 3170.510 3219.694 3268.878
[34] 3318.061 3367.245 3416.429 3465.612 3514.796 3563.980 3613.163 3662.347 3711.531 3760.714 3809.898
[45] 3859.082 3908.265 3957.449 4006.633 4055.816 4105.000

$y
 [1] 39.05844 38.65762 38.25380 37.84773 37.44017 37.03186 36.62354 36.21598 35.80991 35.40608 35.00525
[12] 34.60816 34.21556 33.82819 33.44088 33.04477 32.64639 32.25277 31.87094 31.50659 31.12467 30.72543
[23] 30.33416 29.97614 29.67667 29.41625 29.13676 28.87440 28.64798 28.41000 28.15500 27.88244 27.59175
[34] 27.28236 26.95371 26.61829 26.29738 25.97022 25.64311 25.35443 25.08312 24.80615 24.50784 24.21370
[45] 23.92687 23.64517 23.36640 23.08837 22.80889 22.52576

> 
> # (2) scatter plot, adding smoothed regression line
> with(Cars93, plot(MPG.highway ~ Weight))
> lines(fit_2$x, fit_2$y, col = "blue", lwd = 3)
> title("adding smoothed regression line: lines(), loess.smooth()")
 

 

 

 

 

 

 

> ## drawing horizontal or vertical straight lines : abline()
> with(Cars93, plot(MPG.highway ~ Weight))
> # (1) vertical line
> abline(v = mean(Cars93$Weight), col = "black", lty = 3, lwd = 2) 
> 
> # (2) horizontal line
> abline(h = mean(Cars93$MPG.highway), col = "blue", lty = 3, lwd = 2)
> 
> title("drawing horizontal or vertical straight lines : abline()")

 

 

 

 

다음번 포스팅에서는 points() 함수로 점을 추가하는 방법을 소개하겠습니다.

 

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

 

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

 

 

728x90
반응형
Posted by Rfriend
,

지난번 포스팅에서는 그래프에 추가적인 정보를 입력하는 낮은 수준의 그래프 함수(low level graphic functions) 중에서 첫번째로 제목, XY축 Label 추가하는 title()에 대해서 알아보았습니다.


이번 포스팅에서는 낮은 수준의 그래프 함수 두번째로 (2) XY축 형태 변환 : axis(side, ...) 에 대해서 소개하겠습니다.



[ 낮은 수준의 그래프 함수 (Low level graphic function) ]





XY축 형태를 변경하는 axis() 함수의 기본 사용법은 아래와 같습니다.


axaxis(side, at = NULL, labels = TRUE, tick = TRUE, line = NA,
     pos = NA, outer = FALSE, font = NA, lty = "solid",
     lwd = 1, lwd.ticks = lwd, col = NULL, col.ticks = NULL,
     hadj = NA, padj = NA, ...)




위의 axis() 함수의 모수 중엣서 사용빈도가 높은 주요 모수에 대해서 기능 설명과 예를 들어보겠습니다.  


 arguments

description 

 side

그래프의 어느 쪽에 축을 그릴지 지정하는 정수

(an integer specifying which side of the plot the axis is to be drawn on)

    1 = 아래쪽 (below side)
    2 = 왼쪽 (left side)
    3 = 위쪽 (above side)
    4 = 오른쪽 (right side)

 at

축의 눈금이 그려질 곳의 위치를 지정하는 점들 

(the points at which tick-marks are to be drawn)

 labels

축 눈금에 라벨 데이터를 입력하는 숫자형 벡터, 혹은 문자형 벡터

(numerical or a character or expression vector of labels to be placed at the tick-points) 

 tick

축의 눈금과 축의 선을 그릴지를 설정하는 논리형 값

(a logical value specifying whether tickmarks and an axis line should be drawn) 

 pos

해당 축이 다른 축과 교차하는 좌표

(the coordinate at which the axis line is to be drawn) 

lty 

축과 눈금의 선의 유형

(line type for both the axis line and the tick marks) 

lwd

축의 눈금의 선의 두께

(line widths for the axis line and the tick marks) 

 col

축과 눈금 선의 색깔

(colors for the axis line and the tick marks respectively) 

 tck

 눈금의 방향과 길이 설정

(direction and length of tick marks)

    - 양수 : 그래프 안쪽으로 눈금 생성

    - 음수 : 그래프 바깥쪽으로 눈금 생성

 hadj

 수평 라벨에 대한 수정

(adjustment for all labels parallel (‘horizontal’) to the reading direction)

 padj

 수직 라벨에 대한 수정
(adjustment for each tick label perpendicular to the reading direction)




X축과 Y축을 변경하려면 먼저 "axes = FALSE" 옵션을 사용해서 X축과 Y축을 제거해야 합니다.  X축만 선별적으로 제거하려면 xaxt = "n", Y축만 선별적으로 제거하려면 yaxt = "n" 옵션을 사용하면 되겠습니다.  아래에 각각의 예를 들어보았습니다.


> ##---------------------------------------------
> ## low level graphic functions : axis(side, ...)
> ##---------------------------------------------
> 
> library(MASS) # to use Cars93 dataframe
> 
> # Save default par values
> op <- par(no.readonly = TRUE)
> 
> # Change par() function options
> par(mfrow=c(2, 2)) # make frame by 2 row, 2 columns 
>     
> 
> # plot with X and Y axis
> plot(MPG.highway ~ Weight, Cars93,
+      main = "plot with X and Y axis")
> 
> # deleting X and Y axes : axes = FALSE
> plot(MPG.highway ~ Weight, Cars93, axes = FALSE, 
+      main = "axes = FALSE") 
> 
> 
> # deleting X axis : xaxt = "n"
> plot(MPG.highway ~ Weight, Cars93, xaxt = "n", 
+      main = "xaxt = n") 
> 
> 
> # deleting Y axis : yaxt = "n"
> plot(MPG.highway ~ Weight, Cars93, yaxt = "n", 
+      main = "yaxt = n") 
> 
> 
> # Reset par to the default values at startup
> par(op)



 




X축과 Y축의 범위를 알아보기 위해 summary() 함수로 기술통계량을 알아보겠습니다.


> # summary statistics
> 
> summary(Cars93$Weight) # X axis
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   1695    2620    3040    3073    3525    4105 
> 
> summary(Cars93$MPG.highway) # Y axis
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  20.00   26.00   28.00   29.09   31.00   50.00




X축으로 Weight (차의 무게)를, Y축으로는 MPG.highway (고속도로 연비)으로 하는 산점도를 그린다고 했을 때, X축은 1600~4200까지의 범위로 100씩 증가하는 눈금을, Y축은 18~52까지의 범위로 2씩 증가하는 눈금으로 그려보겠습니다.


> # X axis (1600 ~ 4200, by 100)
> # Y axis (18 ~ 52 range, by 2)
> plot(MPG.highway ~ Weight, Cars93, axes = FALSE, 
+      xlim = c(1600, 4200),
+      ylim = c(18, 52), 
+      main = "scatter plot of Weight and MPG.highway") 
> 
> x <- seq(1600, 4200, by = 100)
> y <- seq(18, 52, by = 2)
> 
> 
> axis(side = 1, # bottom side
+      at = x, 
+      labels = TRUE, 
+      pos = 18, # coordinate of X axis starting point
+      tck = 0.02) # tick marks at vertical direction with 0.02 length
> 
> axis(side = 2, # left side
+      at = y, 
+      labels = TRUE, 
+      pos = 1600, # coordinate of Y axis starting point
+      tck = -0.02) # tick marks at horizontal direction with 0.02 length






다음번 포스팅에서는 직선 연결, 직선 추가하는 낮은 수준은 그래프 함수 lines(), abline() 에 대해서 알아보도록 하겠습니다.


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

 

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

 

728x90
반응형
Posted by Rfriend
,

지난번 포스팅에서는 R Base Graphics plotting system의


(1) 높은 수준의 그래프 함수 (high level graphic functions)

(2) 그래프 모수를 설정하는 2가지 방법 (2 methods of setting graphic parameters)

(3) 그래프 모수 : 기호(symbol), 선(line) 모양 및 크기

(4) 그래프 모수 : 색깔(color)

(5) 그래프 모수 : 그래프 영역 (plot area, inner margin area, outer margin area, multiple plot layout) 에 대해서 소개하였습니다.


높은 수준의 그래프 함수로 그래프의 골격을 만들수 있고, 그래픽 모수로 기호 모양이나 색, 크기 등을 설정할 수 있는데요, 이것 만으로는 원하는 그래프를 만드는데 부족함이 있습니다.  가령 그래프 제목을 추가하고 싶거나, 선이나 점을 추가하고 싶거나, 문자나 범례를 추가하고 싶다거나, XY축을 변경하고 싶을 때가 있는데요, 이때 추가적인 정보를 입력하기 위해 사용하는 것이 '낮은 수준의 그래프 함수 (Low level graphic functions)'가 되겠습니다.


높은 수준의 그래프 함수로 만약 plot(x, y, type = "n") 으로 하면 그래프 창만 열리고 plot area 안에는 빈 공간만 있게 되는데요, 여기에 낮은 수준의 그래프 함수로 그래프 기호, 선, 점, 범례 등을 추가해나갈 수도 있습니다.




이번 포스팅부터 수차례로 나누어서 낮은 수준의 그래프 함수(Low level graphic functions)에 대해서 차례대로 알아보도록 하겠습니다.


[ 낮은 수준의 그래프 함수 (Low level graphic functions) ]





먼저 (1) 그래프 제목(main/sub title) 및 XY축 라벨(XY axis label) 추가하는 방법으로 title() 함수에 대해서 소개해보겠습니다.  title() 함수에 사용하는 옵션으로는 주 제목 main, 부 제목 sub, X축 라벨 xlab, Y축 라벨 ylab 등이 있습니다.


 title(main = "main title to the top of plot in a large font",

      sub = "sub-title sub at the bottom in a smaller font",

      xlab = "x axis label",

      ylab = "y axis label")



이전 포스팅에서 소개했던 높은 수준의 그래프 함수, 즉 hist(), boxplot(), barplot(), plot() 등의 함수 안에서도 주 제목, 부 제목, X축 라벨, Y축 라벨을 직접 지정할 수 있는데요, 아래 예가 높은 수준읙 그래프 함수로 그린 그래프입니다.  


> ##----------------------------------------------
> ## adding main/sub title, XY axis label
> ##----------------------------------------------
> 
> library(MASS) # to use Cars93 dataframe
> 
> # method (1) high level graphic functions : plot()
> plot(MPG.highway ~ Weight, Cars93, 
+      main = "main title : scatter plot of Weight, MPG.highway", 
+      sub = "sub title : plotting with high level graphic functions", 
+      xlab = "x label : Weight", 
+      ylab = "y label : MPG.highway")



 




위의 그래프와 똑같은 그래프를 낮은 수준의 그래프 함수를 사용해서 그려보겠습니다.  먼저 높은 수준의 그래프 함수로는 "ann = FALSE" 옵션을 추가해서 기본 뼈대만 그려보겠습니다.  아래 그래프를 보시면 주 제목, 부 제목, X축 라벨, Y축 라벨이 하나도 없음을 알 수 있습니다.


> # tmheod (2) low level graphic functions : title()
> # deleting X and Y labels : ann = FALSE
> plot(MPG.highway ~ Weight, Cars93, ann = FALSE)



 




위의 기본 뼈대만 있는 그래프에 낮은 수준의 그래프 함수(Low level graphic function)를 사용해서 부가정보를 더해보도록 하겠습니다.


> # adding main title, sub title, x label, y label
> title(main = "main title : scatter plot of Weight, MPG.highway", 
+       sub = "sub title : plotting with low level graphic functions", 
+       xlab = "x label : Weight", 
+       ylab = "y label : MPG.highway")



 



높은 수준의 그래프 함수에서도 주 제목, 부 제목, XY축 Label 등을 설정할 수 있는데 왜 굳이 낮은 수준의 그래프 함수 title() 을 가지고 추가 정보를 입력하는지 의아할 수도 있겠습니다.  높은 수준의 그래프 함수 중에 부가정보를 입력할 수 없는 그래프 함수도 있으며, R의 장점 중에 하나가 대화형으로 그래프의 부가 정보를 차곡 차곡 쌓아가면서, 눈으로 확인해가면서 그릴 수 있어서 굉장히 직관적으로 탐색적 데이터 분석을 할 수 있다는 점입니다. 



참고로, 지난번 포스팅에서 소개한 그래프 모수 (graphics parameters) 중에서 기호의 크기를 설정하는 "cex.main = ", "cex.sub = ", "cex.lab = " 옵션을 사용해서 주 제목, 부 제목, XY축 Label의 크기를 변경해보겠습니다.


 

> # modification of font size : cex.main, cex.sub, cex.lab 
> 
> # deleting X and Y labels : ann = FALSE
> plot(MPG.highway ~ Weight, Cars93, ann = FALSE) 
> 
> # adding main title, sub title, x label, y label
> title(main = "main title with cex 2.2", 
+       sub = "sub title with cex 1.5", 
+       xlab = "x label with cex 1", 
+       ylab = "y label with cex 1", 
+       cex.main = 2.2, # main title size
+       cex.sub = 1.5, # sub title size
+       cex.lab = 1) # x and y label size




다음 포스팅에서는 낮은 수준의 그래프 함수 - (2) XY축 형태 변환 : axis(side, ...) 에 대해서 알아보도록 하겠습니다.


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

 

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


728x90
반응형
Posted by Rfriend
,

지난번 포스팅에서는 R Base Package의 Graphics plotting system의


(1) 높은 수준의 그래프 함수 (high level graphic functions)

(2) 그래프 모수를 설정하는 2가지 방법 (2 methods of setting graphic parameters)

(3) 그래프 모수 : 기호(symbol), 선(line)

(4) 그래프 모수 : 색깔(color)


에 대해서 알아보았습니다.  이번 포스팅에서는


(5) 그래프 모수 : 그래프 영역 (plot area, inner margin area, outer margin area, multiple plot layout) 에 대해서 소개하도록 하겠습니다.



그래프 영역은 크게 (1) 그래프 영역 (plot area), (2) 내부 마진 영역 (inner margin area), (3) 외부 마진 영역(outer margin area) 로 구분할 수 있습니다.  아래의 예시 그래프에 각 영역의 위치에 text 로 표기를 해보았습니다.

 

 

[ 그래프 영역 및 내부/외부 마진 영역 (plot area and inner/outer margin area) ]

 

 

 



  • 그래프 영역 (plot area), 내부 마진 영역 (inner margin area)

(1) 그래프 영역 (plot area)는 점이든 선이든 기호가 그려지는 영역입니다.


(2) 내부 마진 영역 (inner margin area)는 plot area를 감싸고 있는 4개 모서리 부분의 마진입니다.  하단 부분이 1번, 왼쪽 부분이 2번, 상단부분이 3번, 오른쪽 부분이 4번이며, 순서대로 내부 마진 영역의 디폴트 값은 c(5.1, 4.1, 4.1, 2.1) 입니다. 하단은 x축 label, 왼쪽은 y축 label, 상단은 제목이 들어가는 영역이다 보니 디폴트 값의 마진 숫자가 큰 반면에, 오른쪽은 보통은 label이 없으므로 디폴트 마진 값이 타 영역의 반절밖에 안됩니다.


> ##------------------------------------------- > ## Graph Area and Outer/Inner Margin > ##------------------------------------------- > > library(MASS) # to use Cars93 dataframe > > # plotting by default par setting of plot area and inner margin area

> # default inner margin area : c(5.1, 4.1, 4.1, 2.1)

> > plot(MPG.highway ~ Weight, Cars93, type="p", + xlab = "Inner Margin Area 1", + ylab = "Inner Margin Area 2", + main = "Inner Margin Area 3") > > mtext("Inner Margin Area 4", side = 4) > > text(3000, 35, cex = 3, labels = "Plot Area", pos = 3)







  • 외부 마진 영역 (outer margin area)

외부 마진 영역은 내부 마진 영역의 바깥 쪽을 둘러싸는 마진 영역이며, 내부 마진 영역과 위치 순서는 똑같이 하단 부분이 1번, 왼쪽 부분이 2번, 상단 부분이 3번, 오른쪽 부분이 4번입니다.  1번, 2번, 3번, 4번 별로 디폴트 마진 값은 c(0, 0, 0, 0) 입니다.  즉 위의 예의 경우 외부 마진(outer margin) 을 별도로 지정해주지 않았으므로 디폴트 값이 적용되어 외부 마진(outer margin)은 모두 '0' 으로 없는 셈입니다.


외부 마진 영역은 위의 예처럼 1개짜리 그래프에서는 별 쓸모가 없습니다만 (그냥 내부 마진 영역으로 cover 되기 때문입니다), 그래프 영역을 분할해서 2개 이상의 그래프를 하나의 그래프에 결합할 경우 유용하게 사용할 수 있습니다.  개별 그래프에서는 내부 마진 영역에 제목, x축 label, y축 label을 적고, 2개 이상의 개별 그래프들을 모두 아우리는 대제목 (mega title)을 적고자 할 때 외부 마진 영역에 적으면 딱 좋습니다.


아래에 1개의 row, 2개의 column으로 영역을 분할(mfrow = )한 경우 외부 마진 영역 설정(oma = ), 내부 마진 영역 설정(mar = ) 함수의 예를 들어보겠습니다. 외부 마진 부분은 파란색으로 알아보기 쉽게 위치 표시를 했습니다.


참고로, op <- par(no.readonly = TRUE) 로 디폴트 par 값을 미리 할당해두면 나중에 par 값 조정 다 끝나고 원래의 디폴트 값으로 되돌아오고자 할 때 par(op)를 실행시키면 되므로 매우 편리합니다.


> ## -- inner margin area, outer margin area
> # Save default par values, for resetting later
> op <- par(no.readonly = TRUE)
> 
> # Change par() function options
> par(mfrow=c(1,2), # make frame by 1 row, 2 columns 
+     mar=c(4, 3, 3, 1), # inner margin
+     oma=c(0.5, 0.5, 2, 0.5)) # outer margin
> 
> # plot area, inner margin area, outer margin area
> plot(MPG.highway ~ Weight, Cars93, type="p", 
+      xlab = "Inner Margin Area", 
+      main = "Inner Margin Area")
> 
> plot(MPG.highway ~ Horsepower, Cars93, type="p", 
+      xlab = "Inner Margin Area", 
+      main = "Inner Margin Area")
> 
> mtext("Outer Margin Area", outer = TRUE, cex = 2, col = "blue") # outer = TRUE : outer margin area
> 
> 
> # Reset par to the default values at startup
> par(op)



 





  • 영역 분할/결합 방법 1 : par(mfrow = ), par(mfcol = )

2개 이상의 다수의 그래프를 결합하는 방법에는 par() 함수와 layout() 함수의  2가지 방법이 있습니다.  먼저 par() 방법을 살펴보면, par(mfrow = ), par(mfcol = ) 의 2가지 모수 설정 방법이 있습니다. mfrow와 mfcol 은 아래의 말을 줄여 쓴 말입니다.


    - mfrow : number of Multiple Figures (use ROW-wise)

    - mfcol : number of Multiple Figures (use COLUMN-wise)


어렵지 않은 개념이므로 아래에 실제 예를 보면 바로 이해가 될 것이라고 봅니다. par(mfrow = c(4, 2)) 로 해서 4개 row, 2개 column으로 창을 분할해서 총 8개의 그래프를 결합한 예입니다.  그래프가 그려지는 순서를 화살표로 표시를 해두었는데요, 상단 왼쪽에서 시작해서 오른쪽으로 지그재그로 하단으로 내려가면서 그래프가 순차적으로 그려집니다.


> ##-- par(mfrow = ): multiple figures (use ROW-wise)
> par(mfrow=c(4, 2), # make window by 4 row, 2 columns 
+     mar=c(4, 3, 3, 1), # inner margin
+     oma=c(0.5, 0.5, 2, 0.5)) # outer margin
> 
> plot(MPG.highway ~ Weight, Cars93, type="p", main = "plot 1")
> plot(MPG.highway ~ Weight, Cars93, type="p", main = "plot 2")
> plot(MPG.highway ~ Weight, Cars93, type="p", main = "plot 3")
> plot(MPG.highway ~ Weight, Cars93, type="p", main = "plot 4")
> plot(MPG.highway ~ Weight, Cars93, type="p", main = "plot 5")
> plot(MPG.highway ~ Weight, Cars93, type="p", main = "plot 6")
> plot(MPG.highway ~ Weight, Cars93, type="p", main = "plot 7")
> plot(MPG.highway ~ Weight, Cars93, type="p", main = "plot 8")
> 
> mtext("par(mfrow = c(4, 2)", outer = TRUE, cex = 2, col = "blue")





 




이번에는 par(mfcol = c(4, 2)) 설정된 예를 아래에 들어보았습니다. 위의 par(mfrow = c(4,2))처럼 4개의 row, 2개의 column 창이 만들어진 것은 동일합니다만, 그래프가 그려지는 순서는 다름에 유의하시기 바랍니다. par(mfcol = )은 column-wise 기준이어서 위에서 아래로 열이 다 찰 때까지 먼저 그래프가 그려지고, 그 다음에서야 오른쪽으로 넘어가서 다시 위에서부터 아래로 열을 채워가는 식으로 그래프가 순차적으로 그려지는 식입니다.  그래프를 그리고자 하는 순서, 형태에 대해서 먼저 생각을 해보시고, 원하는 순서/형태에 맞게 mfrow와 mfcol 을 선택하면 되겠습니다.

 

> ##-- par(mfcol = ) : multiple figures (use COLUMN-wise)
> par(mfcol=c(4, 2), # make frame by 1 row, 2 columns 
+     mar=c(4, 3, 3, 1), # inner margin
+     oma=c(0.5, 0.5, 2, 0.5)) # outer margin
> 
> plot(MPG.highway ~ Weight, Cars93, type="p", main = "plot 1")
> plot(MPG.highway ~ Weight, Cars93, type="p", main = "plot 2")
> plot(MPG.highway ~ Weight, Cars93, type="p", main = "plot 3")
> plot(MPG.highway ~ Weight, Cars93, type="p", main = "plot 4")
> plot(MPG.highway ~ Weight, Cars93, type="p", main = "plot 5")
> plot(MPG.highway ~ Weight, Cars93, type="p", main = "plot 6")
> plot(MPG.highway ~ Weight, Cars93, type="p", main = "plot 7")
> plot(MPG.highway ~ Weight, Cars93, type="p", main = "plot 8")
> 
> mtext("par(mfcol = c(4, 2)", outer = TRUE, cex = 2, col = "blue")







 



  • 영역 분할/결합 방법 2 : layout()
layout() 함수를 사용하면 행렬(matrix,mat)로 분할하려는 그래프 영역의 순서(sequence)와 열의 폭과 행의 높이(widths of column, heights of row), 영역 나누기/합치기(divide/combine)를 자유롭게 조절할 수 있으므로 위에서 소개한 par(mfrow = ), par(mfcol = ) 보다 사용자에게 보다 높은 자유도를 제공하므로, 매우 유용하고 강력한 함수라고 하겠습니다.  

 

layout() 함수는 par(mfrow = )나 par(mfcol = ) 함수와는 병행해서 사용할 수 없으므로 그래프 분석을 시작하기 전에 무슨 함수를 사용할 것인지 결정을 하고 하나를 선택해야만 합니다.  


layout.show(n)은 현재의 layout에 대한 외곽선을 n 만큼의 그래프 갯수만큼 볼 수 있게 해주는 함수입니다. 

 

아래에 layout()과 layout.show(n) 함수 예를 하나 들어보겠습니다.  matrix() arguments 안의 숫자가 그래프가 그려지는 순서인데요, byrow=TRUE 로 했으므로 상단 왼쪽부터 시작해서 지그재그로 4개의 그래프를 그릴 수 있는 영역을 만들어보았습니다.  byrow= FALSE 로 지정하면 왼쪽 위에서 왼쪽 아래로, 다시 오른쪽 위에서 오른쪽 아래 방향으로 그래프 생성 순서가 설정됩니다.

 

> ##----------------------------------- > ## layout > ##----------------------------------- >

> # Save default par values
> op <- par(no.readonly = TRUE)

>

 

> # divide the divice into 2 rows and 2 columns > # allocate figure 1, 2, 3, 4 from upper left to lower right > layout(matrix(c(1,2,3, 4), 2, 2, byrow = TRUE))

>

> # show the current layout

 

> layout.show(4)

 

 

 

 

 

 

 

 

layout() 함수를 활용하면 그래프 영역을 합칠 수도 있습니다.  이게 par(mfrow = ) 또는 par(mfcol = ) 대비 꽤 유용한 기능 중의 하나입니다.  2 by 2 로 나눈 영역에서 1행 1열에만 그래프 영역 1개를 남겨놓고, 2행의 1열과 2행의 2열은 합쳐보는 예제를 아래에 들어보겠습니다.

 

숫자 '0'은 비어있는 그래프 영역이 되겠으며, 동일한 숫자를 행렬(matrix) 안에 나란히 입력하면 그 영역을 합쳐서 제시하라는 뜻입니다. 아래 예에서는 1행2열에 '0'이 입력되었으므로 비어있고, 2행1열과 2행 2열에 나란히 '2'가 기입되었으므로 2행1열과 2행2열이 합쳐져서 1개의 그래프 영역으로 표시가 되었습니다.

 

> ## divide the device into two rows and two columns
> ## allocate figure 1 the intersection of column 1 and row 1
> ## allocate figure 2 all of row 2
> layout(matrix(c(1,0,2,2), 2, 2, byrow = TRUE))
> 

> ## show the current layout > layout.show(2)

 

 

 

 

 

 

이해를 돕기위해서 이번에는 1행 1열과 1행 2열을 하나로 합치고, 2행 1열은 비워놓고 2행2열만 남겨놓는 layout을 만들어보는 예제를 아래에 들어보겠습니다.  

 

> ## divide the device into two rows and two columns
> ## allocate figure 1 all of row 1
> ## allocate figure 2 the intersection of column 2 and row 2
> 
> layout(matrix(c(1, 1, 0, 2), 2, 2, byrow = TRUE))
> 
> ## show the current layout
> layout.show(2)

 

 

 

 

 

 

이번에는 10cm 정사각형 모양의 그래프 영역을 생성해보겠습니다.  폭은 widths = lcm( ) 으로, 높이는 heights = lcm( ) 으로 설정을 해주면 되겠습니다.

 

> ## create single figure of 10cm square > layout_1 <- layout(matrix(1), widths = lcm(10), heights = lcm(10)) > layout.show(layout_1)

 

 

 

 

 

 

이번에는 그래프 생성 순서(sequence)의 위, 아래를 바꾸어 보고, 그래프의 넓이(widths)와 높이(heights)를 서로 다르게 하는 그래프 영역을 만들어보겠습니다.  가운데에 산포도를 그려놓고 상단과 우측에 작은 크기의 히스토그램이나 박스플롯을 병행해서 그릴 때 유용하게 사용할 수 있습니다.

 

참고로, respect = TRUE 는 가로 넓이와 세로 높이의 비율을 고려해서 그래프 영역을 설정하라는 옵션입니다.

 

> # divide device into two rows and two columns
> # allocate figure 1 the intersection of column 1 and row 2
> # allocate figure 2 the intersection of column 1 and row 1
> # allocate figure 3 the intersection of column 2 and row 2
> # no plot the intersection of column 2 and row 1
> # widths 8cm and 4cm respectively
> # heights 4cm and 8cm respectively
> # respect relations between widths and heights
> 
> layout_2 <- layout(matrix(c(2, 0, 1, 3), 2, 2,byrow = TRUE), 
+              widths = lcm(c(8, 4)), 
+              heights = lcm(c(4, 8)), 
+              respect = TRUE)
> 
> layout.show(layout_2)
> 

 

 
> # Reset par to the default values at startup
> par(op)

 


 

다음번 포스팅에서는 '낮은 수준의 그래프 함수 (Low Level Graphics Functions)'에 대해서 알아보도록 하겠습니다.  앞서의 '높은 수준의 그래프 함수'와 '그래프 모수'에 대해서 예를 들 때 이미 '낮은 수준의 그래프 함수'를 곁들여서 사용하기는 했습니다만, 일목요연하게 한번 더 정리하고 개념을 확실하게 다잡는 다는 의미에서 다음번에 포스팅하도록 하겠습니다.

 

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

 

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


728x90
반응형
Posted by Rfriend
,

지난번 포스팅에서는 R 그래프 모수(Graphical Parameters)를 설정하는 2가지 방법, 선의 유형(Line Type, lty)과 선의 두께(Line Width, lwd), 기호의 크기(Size of Character, cex) 옵션에 대해서 알아보았습니다.


이번 포스팅에서는 그래프 모수 중에서 색깔(color) 설정하는 방법에 대해서 알아보겠습니다.



[ 색 관련 모수 별 기능 설명 ]


 색 관련 모수

(parameters of color)

기능 설명 (description)

 col

 기호, 선, 문자 등의 색깔을 디폴트로 지정 (default plotting color)

 col.axis

 축의 색 지정 (color for axis annotation)

 col.lab

 x축과 y축의 Label 색 지정 (color for x and y labels)

 col.main

 제목 색 지정 (color for main title)

 col.sub

 부제목의 색 지정 (color for sub titles)

 fg

 그래프 전경 색 지정 (color for foreground)

 bg

 그래프 배경 색 지정 (color for background)


아마도 대부분은 col 모수를 주로 사용하고 나머지 색상 관련 모수는 거의 사용하지 않을 듯 합니다만, R에서는 사용자가 원하면 거의 모든 부분의 색상을 원하는대로 설정할 수 있는 극강의 자유도를 제공합니다.  R이 그래픽의 절대강자인 이유가 이처럼 다양한 모수를 제공해주는데 있습니다.  초보자라면 그냥 디폴트 옵션 사용하시면 되구요, 그래프에 욕심이 있는 분이라면 R의 색상 모수에 대해서 차근차근 공부해두시면 유용할 것입니다.


하나씩 차례대로 살펴보도록 하겠습니다.


  • 기호, 선, 문자 등의 디폴트 색 지정 (default plotting color) : col
R에서 지원하는 색의 종류에는 657개가 있습니다.  colors() 함수를 사용하면 657개 전체 색 리스트를 볼 수 가 있습니다.

 

> ##-------------------------------
> ## Graphical parameters : color
> ##-------------------------------
> 
> length(colors())
[1] 657
> 
> colors()
  [1] "white"                "aliceblue"            "antiquewhite"        
  [4] "antiquewhite1"        "antiquewhite2"        "antiquewhite3"       
  [7] "antiquewhite4"        "aquamarine"           "aquamarine1"         
 [10] "aquamarine2"          "aquamarine3"          "aquamarine4"         
 [13] "azure"                "azure1"               "azure2"              
 [16] "azure3"               "azure4"               "beige"               
 [19] "bisque"               "bisque1"              "bisque2"             
 [22] "bisque3"              "bisque4"              "black"               
 [25] "blanchedalmond"       "blue"                 "blue1"               
 [28] "blue2"                "blue3"                "blue4"               
 [31] "blueviolet"           "brown"                "brown1"              
 [34] "brown2"               "brown3"               "brown4"              
 [37] "burlywood"            "burlywood1"           "burlywood2"          
 [40] "burlywood3"           "burlywood4"           "cadetblue"           
 [43] "cadetblue1"           "cadetblue2"           "cadetblue3"          
 [46] "cadetblue4"           "chartreuse"           "chartreuse1"         
 [49] "chartreuse2"          "chartreuse3"          "chartreuse4"         
 [52] "chocolate"            "chocolate1"           "chocolate2"          
 [55] "chocolate3"           "chocolate4"           "coral"               
 [58] "coral1"               "coral2"               "coral3"              
 [61] "coral4"               "cornflowerblue"       "cornsilk"            
 [64] "cornsilk1"            "cornsilk2"            "cornsilk3"           
 [67] "cornsilk4"            "cyan"                 "cyan1"               
 [70] "cyan2"                "cyan3"                "cyan4"               
 [73] "darkblue"             "darkcyan"             "darkgoldenrod"       
 [76] "darkgoldenrod1"       "darkgoldenrod2"       "darkgoldenrod3"      
 [79] "darkgoldenrod4"       "darkgray"             "darkgreen"           
 [82] "darkgrey"             "darkkhaki"            "darkmagenta"         
 [85] "darkolivegreen"       "darkolivegreen1"      "darkolivegreen2"     
 [88] "darkolivegreen3"      "darkolivegreen4"      "darkorange"          
 [91] "darkorange1"          "darkorange2"          "darkorange3"         
 [94] "darkorange4"          "darkorchid"           "darkorchid1"         
 [97] "darkorchid2"          "darkorchid3"          "darkorchid4"         
[100] "darkred"              "darksalmon"           "darkseagreen"        
[103] "darkseagreen1"        "darkseagreen2"        "darkseagreen3"       
[106] "darkseagreen4"        "darkslateblue"        "darkslategray"       
[109] "darkslategray1"       "darkslategray2"       "darkslategray3"      
[112] "darkslategray4"       "darkslategrey"        "darkturquoise"       
[115] "darkviolet"           "deeppink"             "deeppink1"           
[118] "deeppink2"            "deeppink3"            "deeppink4"           
[121] "deepskyblue"          "deepskyblue1"         "deepskyblue2"        
[124] "deepskyblue3"         "deepskyblue4"         "dimgray"             
[127] "dimgrey"              "dodgerblue"           "dodgerblue1"         
[130] "dodgerblue2"          "dodgerblue3"          "dodgerblue4"         
[133] "firebrick"            "firebrick1"           "firebrick2"          
[136] "firebrick3"           "firebrick4"           "floralwhite"         
[139] "forestgreen"          "gainsboro"            "ghostwhite"          
[142] "gold"                 "gold1"                "gold2"               
[145] "gold3"                "gold4"                "goldenrod"           
[148] "goldenrod1"           "goldenrod2"           "goldenrod3"          
[151] "goldenrod4"           "gray"                 "gray0"               
[154] "gray1"                "gray2"                "gray3"               
[157] "gray4"                "gray5"                "gray6"               
[160] "gray7"                "gray8"                "gray9"               
[163] "gray10"               "gray11"               "gray12"              
[166] "gray13"               "gray14"               "gray15"              
[169] "gray16"               "gray17"               "gray18"              
[172] "gray19"               "gray20"               "gray21"              
[175] "gray22"               "gray23"               "gray24"              
[178] "gray25"               "gray26"               "gray27"              
[181] "gray28"               "gray29"               "gray30"              
[184] "gray31"               "gray32"               "gray33"              
[187] "gray34"               "gray35"               "gray36"              
[190] "gray37"               "gray38"               "gray39"              
[193] "gray40"               "gray41"               "gray42"              
[196] "gray43"               "gray44"               "gray45"              
[199] "gray46"               "gray47"               "gray48"              
[202] "gray49"               "gray50"               "gray51"              
[205] "gray52"               "gray53"               "gray54"              
[208] "gray55"               "gray56"               "gray57"              
[211] "gray58"               "gray59"               "gray60"              
[214] "gray61"               "gray62"               "gray63"              
[217] "gray64"               "gray65"               "gray66"              
[220] "gray67"               "gray68"               "gray69"              
[223] "gray70"               "gray71"               "gray72"              
[226] "gray73"               "gray74"               "gray75"              
[229] "gray76"               "gray77"               "gray78"              
[232] "gray79"               "gray80"               "gray81"              
[235] "gray82"               "gray83"               "gray84"              
[238] "gray85"               "gray86"               "gray87"              
[241] "gray88"               "gray89"               "gray90"              
[244] "gray91"               "gray92"               "gray93"              
[247] "gray94"               "gray95"               "gray96"              
[250] "gray97"               "gray98"               "gray99"              
[253] "gray100"              "green"                "green1"              
[256] "green2"               "green3"               "green4"              
[259] "greenyellow"          "grey"                 "grey0"               
[262] "grey1"                "grey2"                "grey3"               
[265] "grey4"                "grey5"                "grey6"               
[268] "grey7"                "grey8"                "grey9"               
[271] "grey10"               "grey11"               "grey12"              
[274] "grey13"               "grey14"               "grey15"              
[277] "grey16"               "grey17"               "grey18"              
[280] "grey19"               "grey20"               "grey21"              
[283] "grey22"               "grey23"               "grey24"              
[286] "grey25"               "grey26"               "grey27"              
[289] "grey28"               "grey29"               "grey30"              
[292] "grey31"               "grey32"               "grey33"              
[295] "grey34"               "grey35"               "grey36"              
[298] "grey37"               "grey38"               "grey39"              
[301] "grey40"               "grey41"               "grey42"              
[304] "grey43"               "grey44"               "grey45"              
[307] "grey46"               "grey47"               "grey48"              
[310] "grey49"               "grey50"               "grey51"              
[313] "grey52"               "grey53"               "grey54"              
[316] "grey55"               "grey56"               "grey57"              
[319] "grey58"               "grey59"               "grey60"              
[322] "grey61"               "grey62"               "grey63"              
[325] "grey64"               "grey65"               "grey66"              
[328] "grey67"               "grey68"               "grey69"              
[331] "grey70"               "grey71"               "grey72"              
[334] "grey73"               "grey74"               "grey75"              
[337] "grey76"               "grey77"               "grey78"              
[340] "grey79"               "grey80"               "grey81"              
[343] "grey82"               "grey83"               "grey84"              
[346] "grey85"               "grey86"               "grey87"              
[349] "grey88"               "grey89"               "grey90"              
[352] "grey91"               "grey92"               "grey93"              
[355] "grey94"               "grey95"               "grey96"              
[358] "grey97"               "grey98"               "grey99"              
[361] "grey100"              "honeydew"             "honeydew1"           
[364] "honeydew2"            "honeydew3"            "honeydew4"           
[367] "hotpink"              "hotpink1"             "hotpink2"            
[370] "hotpink3"             "hotpink4"             "indianred"           
[373] "indianred1"           "indianred2"           "indianred3"          
[376] "indianred4"           "ivory"                "ivory1"              
[379] "ivory2"               "ivory3"               "ivory4"              
[382] "khaki"                "khaki1"               "khaki2"              
[385] "khaki3"               "khaki4"               "lavender"            
[388] "lavenderblush"        "lavenderblush1"       "lavenderblush2"      
[391] "lavenderblush3"       "lavenderblush4"       "lawngreen"           
[394] "lemonchiffon"         "lemonchiffon1"        "lemonchiffon2"       
[397] "lemonchiffon3"        "lemonchiffon4"        "lightblue"           
[400] "lightblue1"           "lightblue2"           "lightblue3"          
[403] "lightblue4"           "lightcoral"           "lightcyan"           
[406] "lightcyan1"           "lightcyan2"           "lightcyan3"          
[409] "lightcyan4"           "lightgoldenrod"       "lightgoldenrod1"     
[412] "lightgoldenrod2"      "lightgoldenrod3"      "lightgoldenrod4"     
[415] "lightgoldenrodyellow" "lightgray"            "lightgreen"          
[418] "lightgrey"            "lightpink"            "lightpink1"          
[421] "lightpink2"           "lightpink3"           "lightpink4"          
[424] "lightsalmon"          "lightsalmon1"         "lightsalmon2"        
[427] "lightsalmon3"         "lightsalmon4"         "lightseagreen"       
[430] "lightskyblue"         "lightskyblue1"        "lightskyblue2"       
[433] "lightskyblue3"        "lightskyblue4"        "lightslateblue"      
[436] "lightslategray"       "lightslategrey"       "lightsteelblue"      
[439] "lightsteelblue1"      "lightsteelblue2"      "lightsteelblue3"     
[442] "lightsteelblue4"      "lightyellow"          "lightyellow1"        
[445] "lightyellow2"         "lightyellow3"         "lightyellow4"        
[448] "limegreen"            "linen"                "magenta"             
[451] "magenta1"             "magenta2"             "magenta3"            
[454] "magenta4"             "maroon"               "maroon1"             
[457] "maroon2"              "maroon3"              "maroon4"             
[460] "mediumaquamarine"     "mediumblue"           "mediumorchid"        
[463] "mediumorchid1"        "mediumorchid2"        "mediumorchid3"       
[466] "mediumorchid4"        "mediumpurple"         "mediumpurple1"       
[469] "mediumpurple2"        "mediumpurple3"        "mediumpurple4"       
[472] "mediumseagreen"       "mediumslateblue"      "mediumspringgreen"   
[475] "mediumturquoise"      "mediumvioletred"      "midnightblue"        
[478] "mintcream"            "mistyrose"            "mistyrose1"          
[481] "mistyrose2"           "mistyrose3"           "mistyrose4"          
[484] "moccasin"             "navajowhite"          "navajowhite1"        
[487] "navajowhite2"         "navajowhite3"         "navajowhite4"        
[490] "navy"                 "navyblue"             "oldlace"             
[493] "olivedrab"            "olivedrab1"           "olivedrab2"          
[496] "olivedrab3"           "olivedrab4"           "orange"              
[499] "orange1"              "orange2"              "orange3"             
[502] "orange4"              "orangered"            "orangered1"          
[505] "orangered2"           "orangered3"           "orangered4"          
[508] "orchid"               "orchid1"              "orchid2"             
[511] "orchid3"              "orchid4"              "palegoldenrod"       
[514] "palegreen"            "palegreen1"           "palegreen2"          
[517] "palegreen3"           "palegreen4"           "paleturquoise"       
[520] "paleturquoise1"       "paleturquoise2"       "paleturquoise3"      
[523] "paleturquoise4"       "palevioletred"        "palevioletred1"      
[526] "palevioletred2"       "palevioletred3"       "palevioletred4"      
[529] "papayawhip"           "peachpuff"            "peachpuff1"          
[532] "peachpuff2"           "peachpuff3"           "peachpuff4"          
[535] "peru"                 "pink"                 "pink1"               
[538] "pink2"                "pink3"                "pink4"               
[541] "plum"                 "plum1"                "plum2"               
[544] "plum3"                "plum4"                "powderblue"          
[547] "purple"               "purple1"              "purple2"             
[550] "purple3"              "purple4"              "red"                 
[553] "red1"                 "red2"                 "red3"                
[556] "red4"                 "rosybrown"            "rosybrown1"          
[559] "rosybrown2"           "rosybrown3"           "rosybrown4"          
[562] "royalblue"            "royalblue1"           "royalblue2"          
[565] "royalblue3"           "royalblue4"           "saddlebrown"         
[568] "salmon"               "salmon1"              "salmon2"             
[571] "salmon3"              "salmon4"              "sandybrown"          
[574] "seagreen"             "seagreen1"            "seagreen2"           
[577] "seagreen3"            "seagreen4"            "seashell"            
[580] "seashell1"            "seashell2"            "seashell3"           
[583] "seashell4"            "sienna"               "sienna1"             
[586] "sienna2"              "sienna3"              "sienna4"             
[589] "skyblue"              "skyblue1"             "skyblue2"            
[592] "skyblue3"             "skyblue4"             "slateblue"           
[595] "slateblue1"           "slateblue2"           "slateblue3"          
[598] "slateblue4"           "slategray"            "slategray1"          
[601] "slategray2"           "slategray3"           "slategray4"          
[604] "slategrey"            "snow"                 "snow1"               
[607] "snow2"                "snow3"                "snow4"               
[610] "springgreen"          "springgreen1"         "springgreen2"        
[613] "springgreen3"         "springgreen4"         "steelblue"           
[616] "steelblue1"           "steelblue2"           "steelblue3"          
[619] "steelblue4"           "tan"                  "tan1"                
[622] "tan2"                 "tan3"                 "tan4"                
[625] "thistle"              "thistle1"             "thistle2"            
[628] "thistle3"             "thistle4"             "tomato"              
[631] "tomato1"              "tomato2"              "tomato3"             
[634] "tomato4"              "turquoise"            "turquoise1"          
[637] "turquoise2"           "turquoise3"           "turquoise4"          
[640] "violet"               "violetred"            "violetred1"          
[643] "violetred2"           "violetred3"           "violetred4"          
[646] "wheat"                "wheat1"               "wheat2"              
[649] "wheat3"               "wheat4"               "whitesmoke"          
[652] "yellow"               "yellow1"              "yellow2"             
[655] "yellow3"              "yellow4"              "yellowgreen"




위처럼 text로 색깔 이름만 있으면 알기 어려울 수도 있는데요, Earl F. Glynn 가 657개 색을 각 숫자별로 그리드에 색을 보기에 좋도록 정리를 해놓았습니다.

[ Color Chart by Earl F. Glynn, Stowers Institute for Medical Research, 24 May 2005 ]

* 출처 : http://research.stowers-institute.org/efg/R/Color/Chart/index.htm




R에서 색을 지정하는 방법에는 (1) 숫자 (index), (2) 색 이름 (color name), (3) 16진수 (hexadecimal), (4) RGB 색상표의 4가지 방법이 있습니다.

 숫자 (index)

색 이름 (color name) 

16진수 (hexadecimal) 

RGB triple 

4

(26번) blue

#0000FF

0  0  255

 NA

(62번) comflowerblue

#6495ED

100  149  237

 NA

(73번) darkblue 

#00008B 

 0  0  139



먼저 (1) 숫자(index)로 지정하는 방법은 편하긴 한데요, 선택할 수 있는 색은 아래와 같이 8가지가 있어서 매우 제한적입니다.

index

 0

 1

3

 color

흰색

(white)

검정색

(black) 

빨강색

(red) 

초록색

(green) 

파랑색

(blue) 

청록색 

(turquoise)

자홍색

(magenta)

노란색

(yellow) 

 회색

(gray)



> # color by index 1~8
> par(mfrow=c(1,2))
> pie(rep(1, 8), col = 1:8)
> pie(rep(1, 16), col = 1:16)



 



반면, (2) 이름(color name), (3) 16진법 표기 (hexadecimal), (4) RGB 색상표 (RGB triple) 은 매우 다양한 색상을 선택할 수 있는 장점이 있습니다.  아래는 Earl F. Glynn 가 작성한 색상표에서 일부를 화면캡쳐한 내용인데요, 모든 색상표는 아래의 출처에 있는 pdf url에 있습니다.

* 출처 : http://research.stowers-institute.org/efg/R/Color/Chart/ColorChart.pdf




파란색(blue)에 대해서 위의 4가지 방법, 즉  (1) 숫자 (index), (2) 색 이름 (color name), (3) 16진수 (hexadecimal), (4) RGB 색상표를 사용해서 R 함수 예를 들어보겠습니다.  파란색(blue)으로 모두 똑같은 결과가 나았습니다.

 

> ## 4 methods of color 'blue' exmaple : index, color name, hexadecimal, RGB
> 
> library(MASS) # to use Cars933 dataframe
> 
> par(mfrow = c(2,2))
> 
> # method 1 : index
> plot(MPG.highway ~ Weight, Cars93, cex = 2, pch = 19, 
+      col = 4, main = "col = 4 (index)")
> 
> # method 2 : color name
> plot(MPG.highway ~ Weight, Cars93, cex = 2, pch = 19, 
+      col = "blue", main = "col = blue (name)")
> 
> # method 3 : hexadecimal
> plot(MPG.highway ~ Weight, Cars93, cex = 2, pch = 19, 
+      col = "#0000FF", main = "col = #0000FF (hexadecimal)")
> 
> # method 4 : RGB triple
> rgb_1 <- rgb(0, 0, 255, maxColorValue=255)
> plot(MPG.highway ~ Weight, Cars93, cex = 2, pch = 19, 
+      col = rgb_1, main = "col = RGB(0, 0, 255)(RGB triple)")






R에서는 색상 관련해서 서로 보완(complementing)되거나 대조를 이루는(contrasting) 색상들을 미리 파레트 형식으로 정의(defined palettes of colors)해 놓은 것이 있습니다.  rainbow(n), heat.colors(n), terrain.colors(n), topo.colors(n), cm.colors(n) 등이 있는데요, example(rainbow) 함수를 이용해서 이들 색상표 palettes 를 살펴보겠습니다. 계속 Enter 치면 다음 화면으로 넘어갑니다.


[ 색상 파레트 (defined palattes of colors) ]

 

> ## example of rainbow palette's colors

> example(rainbow)

rainbw> require(graphics)

rainbw> # A Color Wheel
rainbw> pie(rep(1, 12), col = rainbow(12))



Hit <Return> to see next plot: rainbw> ##------ Some palettes ------------ rainbw> demo.pal <- rainbw+ function(n, border = if (n < 32) "light gray" else NA, rainbw+ main = paste("color palettes; n=", n), rainbw+ ch.col = c("rainbow(n, start=.7, end=.1)", "heat.colors(n)", rainbw+ "terrain.colors(n)", "topo.colors(n)", rainbw+ "cm.colors(n)")) rainbw+ { rainbw+ nt <- length(ch.col) rainbw+ i <- 1:n; j <- n / nt; d <- j/6; dy <- 2*d rainbw+ plot(i, i+d, type = "n", yaxt = "n", ylab = "", main = main) rainbw+ for (k in 1:nt) { rainbw+ rect(i-.5, (k-1)*j+ dy, i+.4, k*j, rainbw+ col = eval(parse(text = ch.col[k])), border = border) rainbw+ text(2*j, k * j + dy/4, ch.col[k]) rainbw+ } rainbw+ } rainbw> n <- if(.Device == "postscript") 64 else 16 rainbw> # Since for screen, larger n may give color allocation problem rainbw> demo.pal(n) Hit <Return> to see next plot: >





  • 축 색 지정 (color for axis annotation) : col.axis
x축과 y축의 척도 표기 색상을 지정할 때 col.axis 모수 옵션을 사용합니다.  아래에 x축과 y축 척도 표기 색상으로 파랑색, 빨강색, 노랑색, 회색으로 바꿔가면서 그래프를 그려보았습니다.

> ## color for axis annotation : col.axis

> library(MASS) # to use Cars93 dataframe > par(mfrow = c(2,2)) > plot(MPG.highway ~ Weight, Cars93, cex = 1, pch = 21, + col.axis = "blue", main = "col.axis = blue") > > plot(MPG.highway ~ Weight, Cars93, cex = 1, pch = 21, + col.axis = "red", main = "col.axis = red") > > plot(MPG.highway ~ Weight, Cars93, cex = 1, pch = 21, + col.axis = "yellow", main = "col.axis = yellow") > > plot(MPG.highway ~ Weight, Cars93, cex = 1, pch = 21, + col.axis = "gray", main = "col.axis = gray")


 





  • x축과 y축 Label 지정 (color for x and y labels) : col.lab
이번에는 x축과 y의 Lable 색을 지정하는 방법으로 col.lab 모수 옵션을 사용하면 됩니다.  파랑색, 빨강색, 노랑색, 회색으로 x축과 y축의 Lable 색을 설정하는 예를 들어보겠습니다.

> ## color for x and y labels : col.lab
> library(MASS)
> par(mfrow = c(2,2))
> plot(MPG.highway ~ Weight, Cars93, cex = 1, pch = 21, 
+      col.lab = "blue", main = "col.lab = blue")
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 1, pch = 21, 
+      col.lab = "red", main = "col.lab = red")
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 1, pch = 21, 
+      col.lab = "yellow", main = "col.lab = yellow")
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 1, pch = 21, 
+      col.lab = "gray", main = "col.lab = gray")



 




  • 제목 색 지정 (color for main title) : col.main
> ## color for main title : col.main
> library(MASS)
> par(mfrow = c(2, 2))
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 1, pch = 21, 
+      col.main = "blue", main = "col.main = blue")
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 1, pch = 21, 
+      col.main = "red", main = "col.main = red")
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 1, pch = 21, 
+      col.main = "yellow", main = "col.main = yellow")
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 1, pch = 21, 
+      col.main = "gray", main = "col.main = gray")



 




  • 부제목 색 지정 (color for sub title) : col.sub
> ## color for sub title : col.sub
> library(MASS)
> par(mfrow = c(2, 2))
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 1, pch = 21, 
+      col.sub = "blue", sub = "col.sub = blue")
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 1, pch = 21, 
+      col.sub = "red", sub = "col.sub = red")
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 1, pch = 21, 
+      col.sub = "yellow", sub = "col.sub = yellow")
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 1, pch = 21, 
+      col.sub = "gray", sub = "col.sub = gray")



 




  • 그래프 전경 색 지정 (color for foreground) : fg
> ## color for foreground : fg
> library(MASS)
> par(mfrow = c(2, 2))
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 1, pch = 21, 
+      fg = "blue", main = "fg (foreground) = blue")
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 1, pch = 21, 
+      fg = "red", main = "fg (foreground) = red")
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 1, pch = 21, 
+      fg = "yellow", main = "fg (foreground) = yellow")
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 1, pch = 21, 
+      fg = "gray", main = "fg(foreground) = gray")


 





  • 그래프 배경 색 지정 (color for background) : bg
bg는 그래프 기호의 배경색을 채울 때 사용합니다.  아래에 기호 모양 21번 (원)에 파랑색, 빨강색, 노랑색, 회색을 채워보았습니다.

> ## color for background :bg
> library(MASS)
> par(mfrow = c(2, 2))
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 2, pch = 21, 
+      bg = "blue", main = "bg (background) = blue")
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 2, pch = 21, 
+      bg = "red", main = "bg (background) = red")
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 2, pch = 21, 
+      bg = "yellow", main = "bg (background) = yellow")
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 2, pch = 21, 
+      bg = "gray", main = "bg (background) = gray")



 




bg (background color)는 속이 비어있는 pch 21번부터 25번 까지만 사용가능하며, 그 외에는 적용이 안됩니다. 아래에 pch =1 일 때 bg 옵션이 적용이 안된 것을 확인할 수 있습니다.

> ## bg (background color) only works with pch from 21 to 25
> 
> library(MASS)
> par(mfrow=c(3,2))
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 2, pch = 1, 
+      bg = "blue", main = "pch = 1, bg is not working")
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 2, pch = 21, 
+      bg = "blue", main = "pch = 21, bg is working")
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 2, pch = 22, 
+      bg = "blue", main = "pch = 22, bg is working")
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 2, pch = 23, 
+      bg = "blue", main = "pch = 23, bg is working")
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 2, pch = 24, 
+      bg = "blue", main = "pch = 24, bg is working")
> 
> plot(MPG.highway ~ Weight, Cars93, cex = 2, pch = 25, 
+      bg = "blue", main = "pch = 25, bg is working")



 



다음번 포스팅에서는 그래프 영역과 내/외부 마진 모수 설정하는 방법에 대해서 알아보도록 하겠습니다.


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

 

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


 

728x90
반응형
Posted by Rfriend
,

지난번 포스팅에서 R 그래프 모수 (Graphical Parameters)를 설정하는 2가지 방법(par(), arguments)에 대해서 소개하였습니다.


이번 포스팅에서는 그래프 모수의 기호, 선 모수 설정에 대해서 하나씩 예를 들어보면서 자세히 설명해보겠습니다.

(그래프 모수가 70여 가지가 되므로 모두를 설명하기에는 무리가 있으며, 자주 사용하는 것들 위주로 선별해서 소개합니다. ?par 로 도움말을 찾아보시면 모든 그래프 모수에 대한 도움말을 검색할 수 있습니다)



  • 기호 (plotting symbols, characters) : pch=
그래픽 모수 pch 를 사용해서 다양한 모양의 기호, 상징을 그릴 수 있습니다.  디폴트는 pch=1 로서 속이 빈 원 모양이며, 아래의 pch 그래픽 모수 숫자별 모양을 참고해서 원하는 모양의 숫자를 pch = '숫자' 로 입력하면 되겠습니다.





MASS 패키지 내 Cars93 데이터프레임의 차 무게(Weight)와 고속도로연비(MPG.highway) 변수를 가지고 산포도 그래프를 아래와 같이 그려보았습니다. pch=1 ~ pch=6 까지 6개만 예로 들어보았습니다.

> ## symbol and character of plotting : pch=
> library(MASS)
> 
> par(mfrow = c(3,2))
> 
> 
> plot(MPG.highway ~ Weight, data = Cars93, pch = 1, main = "pch = 1")
> plot(MPG.highway ~ Weight, data = Cars93, pch = 2, main = "pch = 2")
> plot(MPG.highway ~ Weight, data = Cars93, pch = 3, main = "pch = 3")
> plot(MPG.highway ~ Weight, data = Cars93, pch = 4, main = "pch = 4")
> plot(MPG.highway ~ Weight, data = Cars93, pch = 5, main = "pch = 5")
> plot(MPG.highway ~ Weight, data = Cars93, pch = 6, main = "pch = 6")
> 
> par(mfrow = c(1,1))



 



  • 기호 직접 입력하는 방법 (specifying character directly)
pch = 1 처럼 숫자를 입력하는 방법 말고도 pch = '$', pch = '%', pch = '*'처럼 기호를 직접 pch 다음에 직접 입력해도 됩니다.


> ## specifying character directly
> par(mfrow = c(1,3))
> plot(MPG.highway ~ Weight, data = Cars93, pch = '$', main = "pch = '$' ")
> plot(MPG.highway ~ Weight, data = Cars93, pch = '%', main = "pch = '%' ")
> plot(MPG.highway ~ Weight, data = Cars93, pch = '*', main = "pch = '*' ")


 





  • 기호의 크기 : cex
cex는 기호의 크기를 지정할 때 사용합니다.  cex=1 이 디폴트 크기이며, cex 다음에 입력하는 숫자는 디폴트 대비 상대적인 크기를 나타냅니다.

> ## symbol size : cex > par(mfrow = c(2, 3)) # plot display by 2 row and 3 column > plot(MPG.highway ~ Weight, data = Cars93, pch = 19, cex = 0.5, main = "cex = 0.5") > plot(MPG.highway ~ Weight, data = Cars93, pch = 19, cex = 1, main = "cex = 1 (default)") > plot(MPG.highway ~ Weight, data = Cars93, pch = 19, cex = 1.5, main = "cex = 1.5") > plot(MPG.highway ~ Weight, data = Cars93, pch = 19, cex = 2, main = "cex = 2") > plot(MPG.highway ~ Weight, data = Cars93, pch = 19, cex = 3, main = "cex = 3") > plot(MPG.highway ~ Weight, data = Cars93, pch = 19, cex = 4, main = "cex = 4")


 




  • 선 유형 (line types) : lty
R 그래프 모수에서 제공하는 유형에는 아래과 같이 6개가 있습니다.


> ## line types : lty
> 
> # ordering by Weight
> Cars93_order <- Cars93[order(Cars93$Weight),]
> 
> par(mfrow = c(2, 3)) # plot layout by 2 row and 3 column
> plot(MPG.highway ~ Weight, data = Cars93_order, type = "l", lty = 1, main = "lty = 1")
> plot(MPG.highway ~ Weight, data = Cars93_order, type = "l", lty = 2, main = "lty = 2")
> plot(MPG.highway ~ Weight, data = Cars93_order, type = "l", lty = 3, main = "lty = 3")
> plot(MPG.highway ~ Weight, data = Cars93_order, type = "l", lty = 4, main = "lty = 4")
> plot(MPG.highway ~ Weight, data = Cars93_order, type = "l", lty = 5, main = "lty = 5")
> plot(MPG.highway ~ Weight, data = Cars93_order, type = "l", lty = 6, main = "lty = 6")



 



  • 선 두께 (line width) : lwd
선 두께를 조절하는 그래프 모수는 lwd 입니다. lwd = 1 이 디폴트 값이며, 이 숫자를 기준으로 숫자만큼 선 두께가 배수가 됩니다.  아래에 lwd = 0.5, 1, 2, 3, 4, 5 별로 선 두께가 어떻게 변화하는지 예를 들어보았습니다.  참고로, plot(x, y, dataset, type = "l") 로 하면 선 그래프 (line plot)를 그릴 수 있습니다.

> ## line width : lwd
> 
> # ordering by Weight
> Cars93_order <- Cars93[order(Cars93$Weight),]
> 
> par(mfrow = c(2, 3)) # plot display by 2 row and 3 column
> plot(MPG.highway ~ Weight, data = Cars93_order, type = "l", lwd = 0.5, main = "lwd = 0.5")
> plot(MPG.highway ~ Weight, data = Cars93_order, type = "l", lwd = 1, main = "lwd = 1 (default)")
> plot(MPG.highway ~ Weight, data = Cars93_order, type = "l", lwd = 2, main = "lwd = 2")
> plot(MPG.highway ~ Weight, data = Cars93_order, type = "l", lwd = 3, main = "lwd = 3")
> plot(MPG.highway ~ Weight, data = Cars93_order, type = "l", lwd = 4, main = "lwd = 4")
> plot(MPG.highway ~ Weight, data = Cars93_order, type = "l", lwd = 5, main = "lwd = 5")



 



  • 현재 그래프 모수 확인 (checking current graphical parameter settings) : par()
참고로, par() 함수를 쓰면 현재의 그래프 모수를 확인해볼 수 있습니다. 갯수를 세어보니 총 72개 graphical parameter 가 있네요. 

> # to see current graphical parameter settings
> par()
$xlog
[1] FALSE

$ylog
[1] FALSE

$adj
[1] 0.5

$ann
[1] TRUE

$ask
[1] FALSE

$bg
[1] "white"

$bty
[1] "o"

$cex
[1] 1

$cex.axis
[1] 1

$cex.lab
[1] 1

$cex.main
[1] 1.2

$cex.sub
[1] 1

$cin
[1] 0.2000000 0.2666667

$col
[1] "black"

$col.axis
[1] "black"

$col.lab
[1] "black"

$col.main
[1] "black"

$col.sub
[1] "black"

$cra
[1] 14.4 19.2

$crt
[1] 0

$csi
[1] 0.2666667

$cxy
[1] 0.02623142 0.05008347

$din
[1] 9.277778 7.777778

$err
[1] 0

$family
[1] ""

$fg
[1] "black"

$fig
[1] 0 1 0 1

$fin
[1] 9.277778 7.777778

$font
[1] 1

$font.axis
[1] 1

$font.lab
[1] 1

$font.main
[1] 2

$font.sub
[1] 1

$lab
[1] 5 5 7

$las
[1] 0

$lend
[1] "round"

$lheight
[1] 1

$ljoin
[1] "round"

$lmitre
[1] 10

$lty
[1] "solid"

$lwd
[1] 1

$mai
[1] 1.360000 1.093333 1.093333 0.560000

$mar
[1] 5.1 4.1 4.1 2.1

$mex
[1] 1

$mfcol
[1] 1 1

$mfg
[1] 1 1 1 1

$mfrow
[1] 1 1

$mgp
[1] 3 1 0

$mkh
[1] 0.001

$new
[1] FALSE

$oma
[1] 0 0 0 0

$omd
[1] 0 1 0 1

$omi
[1] 0 0 0 0

$page
[1] TRUE

$pch
[1] 1

$pin
[1] 7.624444 5.324444

$plt
[1] 0.1178443 0.9396407 0.1748571 0.8594286

$ps
[1] 16

$pty
[1] "m"

$smo
[1] 1

$srt
[1] 0

$tck
[1] NA

$tcl
[1] -0.5

$usr
[1] 0 1 0 1

$xaxp
[1] 0 1 5

$xaxs
[1] "r"

$xaxt
[1] "s"

$xpd
[1] FALSE

$yaxp
[1] 0 1 5

$yaxs
[1] "r"

$yaxt
[1] "s"

$ylbias
[1] 0.2

 



다음번 포스팅에서는 색깔과 관련된 그래프 모수에 대해서 알아보도록 하겠습니다.


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

 

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

 

 

728x90
반응형
Posted by Rfriend
,

이전 포스팅에서 Base Graphics plotting system에서 그래프의 기본 골격을 생성하는 높은 수준의 그래프 함수 (High Level Graphics Function)에 대해서 알아보았습니다.


이번 포스팅에서는 그래프의 기호, 선, 색깔, 마진, 영역 분할 등 그래프의 세부적인 옵션들을 설정하는 방법으로 '그래프 모수 (Graphical Parameters)' 에 대해서 소개하겠습니다.


그래프 모수에는 약 70여가지가 있는데요, 포스팅에서 전부 다루기에는 무리가 있어서 활용 빈도가 높다고 생각하는 항목들만을 선별해서 소개하겠습니다.  R의 콘솔 창에 '?par' 라고 입력하면 graphical parameter setting 관련한 도움말을 참고할 수 있습니다.





그래프 모수를 설정하는 방법에는 2가지가 있습니다. 


첫번째 방법은 par() 함수를 이용해서 이후에 생성하는 그래프 전체에 일괄적으로 동일하게 모수를 적용하는 방법입니다 (global environment).  동일한 모수 설정치로 다수의 그래프를 그려야 하는 상황이라면 편리하게 사용할 수 있는 방법입니다.  일부 그래프 모수는 이 첫번째 방법으로만 설정할 수 있습니다. (예: 영역분할 mfrow 등)


두번째 방법은 그래프를 그릴 때마다 매번 함수 내에서 그래프 모수를 일일이 지정해주는 방법입니다.  그래프를 한두개 그리고 말거라거나, 다수의 그래프를 그려야하기는 하는데 모수 설정치가 매번 다르다면 두번째 방법을 사용하는게 편하겠습니다.



[ 그래프 모수를 설정하는 2가지 방법 ]

(2 methods of setting graphical parameters)





(1) 아래에 첫번째 방법으로 par() 함수를 이용해서 그래프 모수를 설정하는 예를 들어보았습니다.  MASS 패키지에 내장되어 있는 Cars93 데이터프레임의 차무게(Weight)와 마력(Horsepower)과 고속도로연비(MPG.highway) 간의 관계를 알아보기 위해 산포도를 그려본 예제입니다.


par() 함수를 사용해서 global environment에 그래프 모수를 설정할 때는 나중에 디폴트 그래프 모수로 돌아와야 하는 상황에서 편리하게 사용할 수 있도록 par(no.readonly = TRUE) 를 par_origin 이라는 객체에 할당해서 저장해 두었다가, 그래프 다 그리고 나서 제일 마지막에 par(par_origin)로 원래의 그래프 모수로 원복하였습니다.


> ##----------------------- > ## Graphical Parameters > > # help on par() function > ?par > > > library(MASS) # to use Cars93 dataframe >

> # method 1 : par() > # saving original graphical parameters setting > par_origin <- par(no.readonly = TRUE) > > # setting new graphical parameters > par(pch = 15, col = "blue") > > plot(MPG.highway ~ Weight, type = "p", Cars93)

> 


> 
> plot(MPG.highway ~ Horsepower, type = "p", Cars93)
> 


> > # returning to original parameter setting > par(par_origin) > plot(MPG.highway ~ Weight, type = "p", Cars93)

> 
> 

 






(2) 두번째로 개별 그래프마다 그래프 모수를 설정하는 방법을 예로 들어보겠습니다.  그래프 결과는 위에서 par()로 그래프 모수 설정했을 때와 동일함을 알 수 있습니다.  그래프를 그려야 하는 상황에 가장 편리한 방법을 선택해서 사용하면 되겠습니다.


> ## method 2 : setting graphical parameters seperately
> plot(MPG.highway ~ Horsepower, type = "p", # scatter plot with point
+      pch = 15, # point character
+      col = "blue", # color
+      data = Cars93)
> 


> 
> 
> plot(MPG.highway ~ Weight, type = "p", # scatter plot with point
+      pch = 21, # point character
+      col = "black", # color
+      data = Cars93)
> 
> 

 




다음번 포스팅에서는 기호, 선, 색깔, 마진, 영역 분할 등의 그래프 모수의 세부 항목들에 대해서 소개하도록 하겠습니다.


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

 

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


 

728x90
반응형
Posted by Rfriend
,

R의 plotting system에는 크게 (1) Base Graphics, (2) Lattice, (3) ggplot2 의 3가지가 있습니다. 이전 포스팅에서 ggplot2 plotting system을 활용한 그래프 그리기를 소개하였다면, 이제부터는 쉽고 빠르게, 대화형으로 직관적으로 그래프를 단계적으로 그려나갈 수 있는 Base Graphics plotting system에 대해서 알아보겠습니다. 


Base Graphics system 은 기본 뼈대에 해당하는 (1) 높은 수준의 그래프 함수 (High Level Graphics facilities), 여기에 살을 하나, 둘씩 차근 차근 더해가는 (2) 낮은 수준의 그래프 함수 (Low Level Graphics facilities), 색깔이나 모양, 선 형태, 마진 등의 다양한 그래프 특성에 해당하는 옵션을 설정하는 (3) 그래픽 모수 (Graphic Parameters) 를 조합하여 단계적으로 (step by step) 그래프를 대화형으로 그려나가게 됩니다.






아래에 산점도(scatter plot)을 가지고 위에서 소개한 용어들이 의미하는 바를 예를 들어 설명해보도록 하겠습니다.



> library(MASS)
> attach(Cars93)
> 
> # high level graphics facility : plot()
> # graphics parameters : type, pch, col, etc.
> plot(MPG.highway ~ Weight, type = "p", pch = 19, col = "black")
> 
> # low level graphics facility : abline(), title(), text()
> # graphics parameters : labels, cex, pos, col, etc.
> abline(lm(MPG.highway ~ Weight))
> text(Weight, MPG.highway, labels = abbreviate(Manufacturer, minlength = 5), 
+      cex = 0.6, pos = 2, col = "blue")

>

> detach(Cars93)


 





위 그래프의 R함수에서 높은 수준의 그래프 함수, 낮은 수준의 그래프 함수, 그래프 모수에 해당하는 부분을 각 각 표기하면 아래와 같습니다.  높은 수준의 그래프 함수 plot()으로 먼저 뼈대를 잡아놓고, 낮은 수준의 그래프 함수 abline()로 차의 무게(Weight)와 고속도로연비(MPG.highway) 간 회귀선을 적합시킨 선을 추가하고 text()로 차 제조사 이름을 명기하였습니다. 이때 그래프 모수(parameters)로 그래프의 형태(type), 점의 형태(pch), 색깔(col), 레이블(labels), default 대비 확대 배수(cex), 다른 축과 교차되는 좌표(pos) 등을 옵션으로 설정하게 됩니다.







높은 수준의 그래프 함수 (High Level Graphics facilities) 들을 표로 정리해보면 아래와 같습니다. 


Graph

High Level Graphics

Functions of Base Graphics system

histogram

hist()

Box-and-Whiskers Plot

boxplot()

Stem and Leaf Plot

stem()

Bar Plot

barplot()

Cleveland Dot Plot

dotchart()

Pie Plot

pie()

Scatter Plot

plot(x, y)

Scatter Plot Matrix

plot(dataframe)

cf) other package: scatterplotMatrx()

Line Plot

plot(x, y, type=“l”)

High Density Needle Plot

plot(x, y, type=“h”)

Both Dot and Line Plot

plot(x, y, type=“b”)

Overlapped Dot and Line Plot

plot(x, y, type=“o”)

  Step Plot

plot(x, y, type=“s”)

Empty Plot

plot(x, y, type=“n”)




디폴트 모수로 해서 간단하게 그래프를 예로 들어보겠습니다.


일변량 연속형 데이터 그래프 (plot for 1 variable, continuous data)

  • Histogram : hist()
> # histogram : hist()
> hist(Cars93$MPG.highway, main = "histogram : hist()")



 



  • box-and-whisker plot : boxplot()
> # box-and-whisker plot : boxplot()
> boxplot(Cars93$MPG.highway, main = "box-and-whisker plot : boxplot()")



 



  • stem and leaf plot : stem()

 

> # stem and leaf plot : stem()
> stem(Cars93$MPG.highway)

  The decimal point is 1 digit(s) to the right of the |

  2 | 00112233334444
  2 | 55555555666666666667777778888888888999999
  3 | 000000000111111123333333444
  3 | 6667778
  4 | 13
  4 | 6
  5 | 0





일변량 범주형 자료 그래프 (plot for 1 variable, categorical data)
  • bar plot : barplot()

 

> ##-------- plot for one variable, categorical data
> # bar plot : barplot()
> table_cyl <- table(Cars93$Cylinders)
> barplot(table_cyl, main = "bar plot : barplot()")





  • Cleveland dot plot : dotchart()
> # cleveland dot plot : dotchart()
> table_cyl <- table(Cars93$Cylinders) # frequency table
> Cylinders <- names(table_cyl) # names for label
> 
> dotchart(as.numeric(table_cyl), labels = Cylinders, main = "cleveland dot plot")



 




  • pie chart : pie()
> # pie chart : pie()
> table_cyl <- table(Cars93$Cylinders) # frequency table
> Cylinders <- names(table_cyl) # names for label
> 
> pie(table_cyl, labels = Cylinders, main = "pie chart")



 





이변량 연속형변수 그래프 (plot for 2 variables, continuous data)
  • 산점도 (scatter plot)
> ##----- plot for 2 variables, continuous data
> # scatter plot : plot(x, y)
> with(Cars93, plot(Weight, MPG.highway, main = "scatter plot : plot(x, y)"))






  • scatter plot matrix : plot(dataframe), pairs(), scatterplotMatrix(dataframe)

>

> # scatter plot matrix : plot(dataframe)

> > 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 ... >

> Cars93_subset <- Cars93[,c("Weight", "Horsepower", "MPG.highway", "MPG.city")]
> plot(Cars93_subset, main = "scatter plot matrix : plot(dataframe)")
> 




>

> # scatter plot matrix : scatterplotMatrix(dataframe)

> library(car) > scatterplotMatrix(Cars93_subset, main = "scatter plot matrix : scatterplotMatrx(dataframe)")

>



 



  • plot by various types : plot(x, y, type = "l, h, b, o, s, n")
> ##--------
> # plot by various type : l, h, b, o, s, n
> # order by Weight
> Cars93_1 <- Cars93[order(Cars93$Weight),]
> 
> # dividing window frame
> par(mfrow = c(3, 2))
> 
> # plots by type
> attach(Cars93_1)


> # line plot
> plot(MPG.highway ~ Weight, type = "l", main = "type = l") 
> 
> # high density needle plot
> plot(MPG.highway ~ Weight, type = "h", main = "type = h") 
> 
> # both dot and line plot
> plot(MPG.highway ~ Weight, type = "b", main = "type = b") 
> 
> # overlapped dot and line plot
> plot(MPG.highway ~ Weight, type = "o", main = "type = o") 
> 
> # step plot
> plot(MPG.highway ~ Weight, type = "s", main = "type = s") 
> 
> # empty plot
> plot(MPG.highway ~ Weight, type = "n", main = "type = n") 
> 
> detach(Cars93_1)




위의 그래프들은 높은 수준의 그래프 함수의 그래프 함수에 대해서 간략하게 소개하기 위해서 모수를 거의 손대지 않고 그린 그래프들입니다. 낮은 수준의 그래프 함수와 주요 모수 (parameter) 설정하는 방법에 대해서는 다음번 포스팅에서 소개하도록 하겠습니다.


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

 

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


 

728x90
반응형
Posted by Rfriend
,

R의 그래프/시각화 기능이 매우 다양함을 그동안의 여러개의 포스팅을 통해서 충분히 피부로 느끼셨을 것으로 생각합니다.  그런데 이게 다가 아입니다.

 

이번 포스팅에서는 Rstudio 에 manipulate 패키지를 설치해서 동적으로 그래프를 조작하는 방법을 소개하겠습니다.  (참고로, R에는 shiny, plotly, rpivotTable 등 동적 그래프, 피봇테이블 지원하는 패키지가 여럿 있습니다)

 

그동안 소개했던 그래프/시각화 방법이 한번 그리고 나면 세팅이 된 상태에서 한번 그려지고 끝입니다.  옵션이나 대상 객체를 바꾸고 싶으면 프로그램 script 창으로 가서 프로그래을 손봐야 하는 번거로움이 있어야 했습니다.

 

하지만, 이번에 소개하는 manipulate 패키지를 활용한 Rstudio 내에서의 동적 그래프 (Interactive Plotting in Rstudio with manipulate package) 를 보시면 편하고 신기하다는 생각을 하게 될 것 같습니다.  manipulate 패키지를 활용하면 동적 그래프 짜는 프로그램이 어렵지도 않습니다.  

 

 

아래의 3개 유형과 이들을 조합한 4번째 예제를 순서대로 소개하겠습니다. 한국말로 번역하려니 쉽지가 않아서 영어 그대로 표기합니다. ^^;

 

  • Slider Control)
  • Picker Control)
  • Checkbox Control)
  • Combining Controls

 

실습에 사용할 데이터는 MASS 패키지에 내장된 Cars93 데이터 프레임의 차종(Type), 가격(Price), 고속도로연비(MPG.highway), 무게(Weight) 변수를 사용하겠습니다.

 

> 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 ... 

 

 

 

(0) manipulate package installation

 

먼저, manipulate 패키지를 별도 설치하고 호출해 보겠습니다.  

 

 
> install.packages("manipulate")
Installing package into ‘C:/Users/user/Documents/R/win-library/3.2’
(as ‘lib’ is unspecified)
trying URL 'http://cran.rstudio.com/bin/windows/contrib/3.2/manipulate_1.0.1.zip'
Content type 'application/zip' length 35812 bytes (34 KB)
downloaded 34 KB

package ‘manipulate’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
	C:\Users\user\AppData\Local\Temp\RtmpGaEGZu\downloaded_packages
> library(manipulate)

 

 

 

 

(1) Slider Control

 

slider(start point, end point, step= , initial = ) 의 형태로 슬라이더 조작 옵션을 설정하고, 이 옵션 객체를 그래프의 조작하고자 하는 부분에 할당을 하면 됩니다.  말이 좀 어려운데요, 아래 히스토그램에서 Bin size 를 3부터 100까지의 범위 내에서 5 씩 증가하게끔 해놓고, 처음 만들어졌을 때의 디폴트는 20으로 설정한 예제입니다.  동적 그래프의 특성을 직관적으로 이해할 수 있도록 화면캡쳐와 함께 동영상 캡쳐도 해서 올립니다.  왼쪽의 슬라이드 바를 좌우로 조절할 때마다 우측 plots 창의 히스토그램이 어떻게 바뀌는지 확인해보기 바랍니다.

 

 
> library(MASS)
> ## Slider Control
> 
> manipulate(
+   hist(Cars93$Price, breaks = bin_slider),  
+   
+   bin_slider=slider(3,100, step=5, initial = 20))

 

 

 

 

 

 

 

 

 

 

 

(2) Picker Control

 

히스토그램에 대상 변수를 선택할 수 있는 Picker Control 예제입니다.

 

 
> ## Picker Control
> 
> manipulate(
+   hist(Cars93[, continuous_variable], 
+           freq = FALSE, main = continuous_variable),
+   
+   continuous_variable = picker("MPG.highway", "Weight", "Price"))
 
 
 

 

 

 

 

 

 

산포도의 x축, 무게(Weight)과 y축, 고속도로연비(MPG.highway)은 정해져있고, 차종(Type)별로 산포도를 보고 싶을 때 차종(Type)을 왼쪽의 Picker Control 상자로 만들어서 바로 바로 차종별로 선택해 가면서 산포도를 보는 프로그램 예제입니다.

 

 
> manipulate(
+   plot(MPG.highway ~ Weight, data=Cars93[Cars93$Type == Type,]),
+   
+   Type = picker("Compact", "Large", "Midsize", "Small", "Sporty", "Van"))

 

 

 

 

 

 

 

 

 

 

 

(3) Checkbox Control

 

아래는 Box Plot 에서 IQR(Inter Quartile Range)의 1.5배 기준으로 계산된 Outlier 를 포함시켜서 제시를 할지 아니면 제외시킬지를 Checkbox 로 선택할 수 있게 한 예제입니다.

 

 
> ## Checkbox Control
> 
> manipulate(
+   boxplot(Price ~ Type, data = Cars93, outline = outline),
+   
+   outline = checkbox(FALSE, "Show outliers"))
 

 

 

 

 

 

 

 
 

 

 

 

(4) Combining Controls

 

이번에는 Picker Control과 Slider Control 두 개를 함께 사용해 보는 예제입니다.  Picker Control 로 대상 변수를 선택할 수 있게 하였고, Slider Control 로 Histogram 의 Bin size 를 조절할 수 있도록 해보았습니다.

 

 
> ## Combining Controls
> 
> manipulate(
+   hist(Cars93[, continuous_variable], 
+        breaks = bin_slider, 
+        freq = FALSE, main = continuous_variable),
+   
+   continuous_variable = picker("MPG.highway", "Weight", "Price"), 
+   bin_slider = slider(5,50, step=5, initial = 10)
+   )
 
 
 

 

 
 

 

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

 

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

 

 

728x90
반응형
Posted by Rfriend
,