지난번 포스팅에서는 그래프에 추가적인 정보를 입력하는 낮은 수준의 그래프 함수(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)

(5) 문자 추가 : text(x, y, labels, ...), mtext()

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

 


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



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

 

 

 

범례를 추가하는 legend()함수의 일반적인 사용법은 아래와 같습니다.

 

legend(x, y = NULL, legend, fill = NULL, col = par("col"),
       border = "black", lty, lwd, pch,
       angle = 45, density = NULL, bty = "o", bg = par("bg"),
       box.lwd = par("lwd"), box.lty = par("lty"), box.col = par("fg"),
       pt.bg = NA, cex = 1, pt.cex = cex, pt.lwd = lwd,
       xjust = 0, yjust = 1, x.intersp = 1, y.intersp = 1,
       adj = c(0, 0.5), text.width = NULL, text.col = par("col"),
       text.font = NULL, merge = do.lines && has.pch, trace = FALSE,
       plot = TRUE, ncol = 1, horiz = FALSE, title = NULL,
       inset = 0, xpd, title.col = text.col, title.adj = 0.5,
       seg.len = 2) 

 

 

옵션이 굉장히 많지요?  ^^;  그래프에 관한한 R 가지고 못하는게 거의 없다는게 바로 이런 겁니다.  그런데 이걸 다 설명하자니 시간이 너무 오래걸릴것 같기도 하고 대부분은 아마 거의 사용할 일이 없을 것 같기도 합니다.  그래서 많이 사용하는 옵션 위주로 몇 개만 선별해서 어려움없이 사용할 수 있는 정도로만 설명하겠습니다.

 

 

 구분

옵션 기능 

 x, y

  범례를 추가할 위치를 설정하는 3가지 방법

  (1) x, y 좌표를 입력하면 범례 사각형의 왼쪽 상단이 그 지점에 위치함

  (2) locator(1)을 입력하면 커서를 가리키는 지점에 범례 생성

  (3) 위치를 나타내는 아래의 9개 단어 중 하나를 선택해서 입력

    : "bottomright", "bottom", "bottomleft", "left", "topleft",

      "top", "topright", "right" and "center"

 legend

  길이가 1보다 큰 문자(character) 혹은 범례를 담은 벡터(expression vector)

 col

  색깔 지정 벡터

 lty

  선 유형 지정 벡터

 lwd

  선 두께 지정 벡터

 pch

  기호 지정 벡터

...

  그래픽 모수 추가 설정 가능

 

 

 

MASS 패키지에 내장된 Cars93 데이터프레임의 차종(Type) 별로 차 무게(Weight)와 고속도로 연비 (MPG.highway) 변수를 사용해서 산포도를 그려보겠습니다. 그리고 차종(Type) 그룹에 대한 범례(legend)를 추가해보겠습니다.

 

 

(1) x, y 좌표를 직접 입력하여 범례 위치 설정

 

> # to use Cars93 dataframe
> library(MASS)
> 
> # scatter plot
> attach(Cars93)
> 
> # adding points with different characters by condition
> plot(Weight, MPG.highway, type = 'n') # blank plot
> 
> # 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 legend to the plot")
> 
> 
> # adding legend to topright side
> legend(x = 3500, y = 50, 
+        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)

 

 

 

 

(2) 위치를 나타내는 말을 직접 입력하여 범례 위치 설정

 

> library(MASS)
> # scatter plot
> attach(Cars93)
> # adding points with different characters by condition
> plot(Weight, MPG.highway, type = 'n') # blank plot
> # 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)

 

 

 

다음번 포스팅에서는 다각형(polygon)을 추가하는 방법에 대해서 소개하겠습니다.

 

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

 

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

 

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)

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

 


이번 포스팅에서는 낮은 수준의 그래프 함수 네번째로 (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
,