동기부여(motivation)에 관한 수많은 책들이 서점에 있습니다만, 이번 포스팅에서는 Daniel H. Pink의 'Drive'라는 책을 추천하고 싶습니다. 직장, 학교, 학원, 교회 공동체 등 사람이 모인 곳이면 어느 곳이던지 간에 추천하고픈 책입니다.

 

이 책의 영어 부제목이 "The Surprising Truth About What Motivates Us" 입니다.  저는 리더십의 핵심이 "동기부여"라고 생각하는데요, 이 책을 리더십에 관심있는 분이라면 꼭 읽어보시면 좋겠습니다.

 

Daniel H. Pink는 미래학자 이면서 저술가이고 뉴욕타임즈, 하버드 비즈니스 리뷰 등에 글을 기고하는 언론인이기도 합니다.  심리학, 과학, 경제학 등의 경계를 넘나들며 전문가들의 알아듣지 못할 기호가 아니라 일반인들도 쉽게 이해할 수 있는 용어로 쉽게 풀어쓴 교양서를 맛갈나게 쓰는 분입니다.

 

 

 

 

이 책에서 저자는 동기 1.0, 동기 2.0, 동기 3.0 으로 구분하여 설명하고 있습니다. 동기 1.0은 생존을 위한 의, 식, 주에 대한 1차적인 욕구를 말합니다. 동기 2.0은 스키너의 S(stimulate)-R(response) 모델처럼 보상과 처벌에 반응한다고 가정합니다. Daniel H. Pink가 주장하는 동기 3.0은 인간에게는 제3의 드라이브(배우고 창조하고 이 세계를 나은 곳으로 만들고 싶다는 욕구)가 있다고 가정합니다.

 

저자는 동기 3.0의 주장의 근거로 다양한 심리 심험 결과를 제시합니다. 아래에 몇 개 예를 클립해서 소개합니다.

 

p64~65. 톰소여 효과
 
 에머빌과 동료 두 명은 고객의 의뢰를 받거나 받지 않고 창작활동을 하는 미국의 전문 화거 23명을 선정했다. 그들은 화가들에게 자신의 작품 중에서 작품 10점을 임의로 선택하게 했다. 그 후 이 실험에 대해 전혀 알지 못하는 권위 있는 예술가와 큐레이터로 구성된 전문가 집단에게 이 작품들을 보내면서 각 작품의 창의성과 기술적인 면을 평가해달라고 요청했다.
 
 "우리는 굉장히 놀라운 결과를 얻었다. 고객의 의뢰를 받은 작품이 의뢰받지 않은 작품에 비해 창의성이 상당히 부족했으나 기술적인 면은 별반 다르지 않았다. 또한 화가들은 의뢰받지 않은 작업보다는 의뢰받은 작업을 할 때 훨씬 더 많은 제약을 느꼈다고 보고했다"고 연구자들은 말했다.
 
 연구자들과 인터뷰했던 한 화가는 자신의 톰소여 효과를 이렇게 묘사했다.
 
 "다른 사람을 위해 작업할 때면 항상 그런 것은 아니지만 많은 경우에 작업이 즐거움보다는 '일'에 가까워진다. 반면 나 자신을 위해 작업할 때는 창조한다는 순전한 즐거움을 느끼면서 밤을 새는지도 모르고 일하기도 한다. 의뢰받은 작업의 경우는 스스로를 억제하고 고객의 요구를 따르기 위해 정신을 바짝 차려야 한다."
 

 

 

p65~67. 이상한 나라의 엘리스 역설
 
 이보다 더 오랜 기간에 걸쳐 화가들을 관찰한 또 다른 연구에서도 외적 보상에 대해 관심을 보이면 실제적으로 궁극적인 성공에 방해를 받을 수 있다는 점이 확인되었다.
 1960대 초 시카고 예술대학교의 2~3학년 학생들을 대상으로 일에 대한 태도와 외재 동기와 내재 동기의 영향력에 대한 연구가 실시되었다. 그리고 1980년대 이르러 또 다른 연구자가 이 연구자료를 바탕으로 과거 학생들의 경력을 추적해본 결과 특히 남학생의 경우 가장 놀라운 결과가 드러났다.
 
 "예술학교에 재학할 당시 외재 동기가 적은 학생일수록 졸업하고 몇 년 후와 거의 20년 후에 전문예술분야에서 성공하는 확률이 높았다."
 
 내재 동기가 풍부했던 화가와 조각가, 다시 말해서 발견의 즐거움과 창조의 도전을 보상으로 여기는 이들은 예술가라면 마땅히 겪게 마련인, 아무런 보상이나 인정을 받지 못하는 고통스러운 시간을 견뎌냈다. 이 연구결과 역시 제3의 드라이브라는 '이상한 나라의 엘리스'의 또 다른 역설에 이른다.
 
 "외적 보상보다 행위 자체의 즐거움을 위해 회화와 조각을 추구한 예술가들이 결국에는 사회에서 탁월성을 인정받는 예술을 창조했다. 외적 보상에 가장 영향을 받지 않은 이들이 마침내 외적 보상을 받게 된다."
 
 ...(중략)... 에머빌 등은 오랜 시간에 걸쳐 이 현상을 연구한 끝에 사회과학분야에서 가장 견고한 영역으로 발전시켰다. 예술가와 과학자, 발명가, 학생, 그리고 우리 같은 보통사람들에게도 내재 동기, 즉 흥미롭고 도전적임 무척 재미있어서 어떤 일을 하고 싶다는 동기는 높은 수준의 창의성을 요구하는 일에 반드시 필요하다. 반면 업무 대부분의 기초가 되는 '만약-그러면'의 조건부 외재 동기는 창의적인 사고를 자극하기보다 말살하는 경우가 많다.
 우리 경제가 개념적인 우뇌작업으로 기울고 자신의 양초 문제를 해결해야 하는 사람들이 증가하면서 이 점이야말로 과학이 밝혀낸 내용과 실제적으로 행해지는 일 사이에서 가장 우려할 만한 괴라가 될 수도 있다.
 
p73~74. 목표 설정의 부작용
 
 물론 모든 목표가 동등한 것은 아니다. 또한 목표와 외적 보상이 본질상 부패한 것이 아니라는 점도 강조하고 싶다. 그러나 목표에는 동기 2.0이 인정하는 것 이상의 독성이 있다. 경영대학 교수들은 목표에 다음과 같은 경고문이 추가되어야 한다고 말한다.
 
"목표는 초점을 편협하게 만들고 비윤리적인 행동을 야기하며 위험을 증가시키고 협동심과 내재 동기를 줄이기 때문에 관련 조직에 체계적인 문제를 야기할 수도 있습니다. 조직에 목표를 적용할 경우 주의가 필요합니다"
 
p83. 외적보상과 근시안적 사고
 
사람들은 외적 보상이 두드러지는 환경에서는 보상을 유발하는 지점까지만 노력하고 그 이상은 애쓰지 않는다. 그래서 책을 세 권 읽으면 상을 준다고 제시하면 많은 학생들이 네 번째 책을 읽지 않을 것이며, 평생 독서의 길에 들어서지도 않을 것이다. 4분기 수익을 달성한 경영진이 회사의 장기 전망에 대해 고민하지 않는 것은 물론이고, 정해진 수익에서 1원이라도 더 벌려고 하지 않는 것이나 마찬가지이다. 또한 사람들에게 운동이나 금연 혹은 약을 복용하면 돈을 준다고 제시하면 처음에는 좋은 결과를 얻을 수 있지만 인센티브가 제거되는 순간 건전한 행동도 사라진다.
* 출처 : Drive, by Daniel H. Pink
 
 
위에서 소개한 책의 일부 내용을 읽다보면 현재 대부분의 기업에서 가정하고 있는 인간형은 더글러스 맥그리거의 X이론 ("인간은 게으르고, 편한 것을 좋아하고, 자발성이라고는 없으므로, 당근과 채찍으로 몰아가야 한다")에 입각한 동기 2.0 에 머물러 있는 것 같습니다.
 
"If xxxx 하면 then xxxx 인센티브 보너스 부여"하겠다는 조건부 보상체계를 운영하고 있는 경우가 많기 때문입니다. 그리고 "올해 매출 목표 xxx억원, 이번 분기 당기순이익 목표 xxx억원" 같이 KPI 목표설정 후 조직단위로 cascading 하고 몰아붙이는 형태가 많기 때문입니다.
 
경제학자들이 굉장히 중요하게 주제 중의 하나가 "보상체계"인데요, 스키너의 S(자극)-R(반응) 모델에 입각한 동기 2.0 을 신봉하는 경제학자들의 경우에는 이 책을 읽으면 아마 심한 충격을 받지 않을까 싶습니다.
 
창의성과 혁신이 중요한 시기에는 경제 2.0의 동기부여체계가 도리어 창의성을 죽이는 역할을 한다는 것이 이 책의 주장이거든요.
 
저자 Daniel H. Pink 는 동기부어의 세 가지 요인으로 (1) 자율성 (자기주도적인 동기부여의 힘), (2) 숙련 (몰입에 이르는 길), (3) 목적 (의미있는 삶) 을 들고 있습니다.
 
조직의 리더라면, 리더십에 관심이 있는 분이라면 이 세가지, 자율성, 숙련, 목적을 한번 음미해보고 조직에, 조직원에게 적용해보면 좋겠습니다.
 
요즘 미국에서 잘나가는 기업들로 애플, 구글, 페이스북, 넷플릿스, 우버, 테슬라 등을 들 수 있을 텐데요, 소위 이들 뜨는 기업들은 더글러스 맥그리거의 Y이론("인간에게 일이 놀이나 휴식처럼 자연스러우며, 이니셔티브와 창의성이 만연해 있으며, 사람들이 특정 목표에 전념하면 책임을 지고 싶어한다")에 입각해서 Daniel H. Pink 가 주장하는 동기 3.0 에 입각한 HR체계가 잡혀있을것 같습니다. (사실관계 확인 안하고 이렇게 쓰는게 좀 무책임한 포스팅인것 같긴 합니다만.... ^^;)  페이스북의 해커톤이라든지, 구글의 15% 룰 등이 자율성의 예에 해당이 될 것 같습니다.  이들 회사가 몇 년, 몇 십년 경력의 소프트웨어 엔지니어를 우대하고 억대 연봉의 보상을 해준다는 점을 보면 '숙련'된 엔지니어의 값어치를 이들 회사가 인정하고 인재를 끌어들이고 있다고 봐야하겠지요. 애플의 전 CEO 스티브 잡스가 했던 말 "우주에 (의미있는) 흔적을 만들어라(Make a Dent in the Universe)"이 목적에 근접한 말이 아닐까 싶습니다.

 

동기 2.0과 동기 3.0 간의 간극은 화성인과 금성인 간의 차이만큼이나 크고 넓습니다.  혹시 조직의 일이 "시키는대로 아무 생각없이 해도 되는 일"이라면 동기 2.0에 입각한 HR체계로도 문제가 없으며, 향후 10년 이내에 로봇, SW로 대체할 수도 있을 것으로 예상합니다.

 

반면에 조직의 일의 성격이 "정해진 틀이 없고, 매뉴얼이 없고, 창의성과 혁신이 필요한 업무"라면 동기 3.0에 입각한 동기부여에 대해서 진지하게 고민하고 변화를 모색해봐야 하지 않을까요?  Daniel H. Pink의 "Drive"가 좋은 지침서가 될 수 있을 것 같습니다.

 

교육자나 자녀 교육, 양육에 관심이 많은 부모들도 이 책에 주목하면 좋겠습니다.  혹시 자녀에게 "이번 기말고사에서 올 백 받아오면 아이폰 사줄께"라고 말하는 부모는 아닌지요?  혹시 "이 방 청소하면 용돈 5천원 줄께"라고 말하는 부모는 아닌지요?  혹시 "성경책 다 읽거나 전도 1명 하면 문화상품권 1만원권 줄께" 라고 말하는 교회 선생님은 아닌지요?  혹시 "내일까지 독일어 정관사 규칙 못 외우면 손바닥 3대씩 맞는다"고 말하는 학교 선생님은 아닌지요?  혹시라도 이에 해당한다면 자녀의 내재동기, 자율성에 심각한 상처와 부작용을 남기고 있을 가능성이 매우 높습니다.  한마디로 자녀와 학생을 물질적인 보상이나 처벌에 대한 협박 없이는 어떻게 할 수 없게끔 아이를 망치고 있다는 얘기입니다. 독이 아니라 약이 되는 보상과 처벌, 칭찬을 구별해서 자녀에게, 학생에게 좋은 영향력을 행사하고 싶다면 이 책이 역시 좋은 길잡이가 될 듯 합니다.

 

3년 전에 한번 읽고, 며 칠전에 한번 더 읽은 책이었는데요, 가슴을 울리는 것이 있었고, 그래서 같이 공간에서 같이 일하는 분들과 함께 토론해보고 싶은 책이었습니다. 아래에 책 "Drive" 목차 곁들여서 소개하는 것으로 이번 포스팅을 마칠까 합니다.

 

 

[ "Drive" 목차 ]

 

1부. 동기부여에 관한 새로운 운영체계

  1장. 동기 2.0의 부상과 몰락

         당근과 채찍의 승리

         호환 불가능한 세 가지 문제점

 

  2장. 당근과 채찍이 효과가 없는 일곱 가지 이유

         원하는 것은 그 이하로

         원하지 않는 것은 그 이상으로

 

 3장. I유형과 X유형

        알파벳의 힘

        I유형과 X유형

 

2부. 동기부여의 세가지 요인

 4장. 자율성, 자기주도적인 동기부여의 힘

       선수인가, 장기알인가?

       네 가지 필수적인 요인

       자율성의 기술

 

  5장. 숙련, 몰입에 이르는 길

       순종에서 참여로

       화물선의 골디락스

       숙련의 세 가지 법칙

       영혼의 산소

 

   6장. 목적, 의미 있는 삶

       목적 동기

 

3부. I유형의 툴키트

      개인을 위한 I유형

      조직을 위한 I유형

      보상의 선 禪

      부무와 교육자를 위한 I유형

      필독 도서 15권

      대가들의 이야익

      I유형의 훈련 계획

 

 

 

 

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
,

지난번 포스팅에서 벡터의 곱 첫번째로 내적 (inner product, dot product, scalar product, projection product)에 대해서 알아보았습니다.

 

이번에는 벡터의 곱 두번째로 벡터곱(vector product, cross product)과 외적 (outer product)에 대해서 알아보도록 하겠습니다.  

 

아래에는 내적과 벡터곱(vector product, cross product) 비교한 표입니다. 처음 보면 잘 이해가 안갈 수도 있는데요, 아래의 내용을 한번 쭉 보시고 마지막에 요약 정리할 때 참고하시면 도움이 될 듯 합니다. 큰 차이점 하나만 들자면, 내적(inner product)은 계산 결과로 스칼라(scalar)가 되지만, 벡터곱(vector product)은 계산 결과가 두 벡터 a와 b에 수직이 되는 벡터(vector)가 되고, 외적(outer product)은 행렬(matrix)가 된다는 점입니다. 

 

 

[ 내적와 벡터곱 비교 ]

(comparison between inner product and vector product)

 

vector product, cross product, directed area product

 

먼저 벡터곱(vector product, cross product, directed area product)에 대해서 차근차근 설명해 보겠습니다. 그리고 마지막에 외적(outer product) 계산법에 대해서 간략히 소개하겠습니다. 

 

 

(1) 벡터곱의 표기 (notation and symbol of vector product)

 

두 벡터 a, b의 벡터곱은 a x b 라고 쓰고 "a cross b"라고 읽습니다.  벡터곱을 교차곱 (cross product)이라고도 부르는 이유가 여기에 있습니다.  (참고로, 내적은 a·b 로 표기하고 a dot b 라고 읽으며 dot product 이라고도 함)

 

 

 

(2) 벡터곱의 정의 (definition of vector product) 

 

두 벡터 a와 b에 모두 수직이 되는 벡터로서, v와 수직이 되는 두 벡터 a와 b는 공간 속의 평면 위에 있는 한 평행사변형의 두 변을 이루게 되며, 그 벡터의 길이(힘의 크기) |v|는 평행사변형의 면적과 같습니다.

 

 

 

 

 

 

(3) 벡터곱 계산을 쉽게 기억하는 방법 (easy way to memorize vector product calculation)

 

내적 대비 벡터곱 계산하는 방법이 많이 어려워보일 수 있는데요, 아래처럼 벡터 a와 b의 component를 두번씩 세로로 써 놓고 두번재째 행부터 순차적으로 대각선으로 곱하고 빼나가면 v1, v2, v3를 구할 수 있습니다.

 

 

 

 

(4) 벡터곱을 계산하는 R 사용자 정의 함수 (R user-defined function of vector product)

 

벡터곱(vector product, cross product)을 구하는 R 패키지, 함수가 분명 있을 것 같은데요, 제가 아직 못찾았습니다.  그래서 위에 소개한 공식대로 아래에 사용자 정의함수 프로그래밍 한거 소개합니다.  혹시라도 외적 구하는 R 패키지랑 함수 알고 계신분은 댓글로 공유해주시면 감사하겠습니다. 

 

##--------- 
# (2) cross product of vector with 3 components : user defined function 
# a * b = |a|*|b|*sin(theta)*n
 
cross_prod_fun_v3 <- function(a, b) { 
     if(length(a)!=3 | length(b) !=3) stop('number of vector component is not 3') 
     
     c_x <- a[2]*b[3] - a[3]*b[2] 
     c_y <- a[3]*b[1] - a[1]*b[3] 
     c_z <- a[1]*b[2] - a[2]*b[1] 
     cross_prd <- c(c_x, c_y, c_z) 
     
     return(cross_prd) 
 } 

a <- c(2, 3, 4) 
b <- c(5, 6, 7) 

cross_prod_fun_v3(a=a, b=b) 
[1] -3 6 -3

 

 

R의 %*%, crossprod() 함수는 외적이 아니라 내적을 계산한 결과를 내보내주므로 헷갈리지 않도록 해야겠습니다.  아래에 a=(2, 3, 4)와 b=(5, 6, 7) 벡터를 가지고 %*%, crossprod() 함수를 적용해봤더니 내적으로 계산해서 스칼라(scalar)가 나온것을 알 수 있습니다. (not vector, but scalar)

 

# cautions: crossprod() function of R produces dot product, not cross product 
a <- c(2, 3, 4) 
b <- c(5, 6, 7) 

a %*% b 
# dot product [,1] [1,] 56 


crossprod(a, b) 
# is the same with dot product [,1] [1,] 56 


t(a) %*% b # is the same with dot product [,1] [1,] 56

 

 

 

(5) 오른손 법칙 (Right-handed triple), 오른손 직교좌표계 (Right-handed Cartesian coordinate system)

 

a와 b 두 벡터의 벡터곱이 벡터 a와 b에 직교 (right angle)하는 외적 v 벡터의 방향을 알 수 있는 방법으로 오른손 좌표계(Right-handed Cartesian coordinate system)을 사용합니다.  오른손의 엄지가 벡터 a, 오른손의 검지가 벡터 b, 그리고 오른손의 중지를 엄지와 검지랑은 수직이 되게 폈을 때가 외적 벡터 v 가 되겠습니다.  아래 그림을 참고하시지요. 

 

 

오른손 법칙은 오른손 나사를 연상해도 되는데요, 벡터 a를 벡터 b의 방향으로 각도 θ만큼 회전시켰을 때 오른손 나사가 나아가는 방향과 같은 방향이 외적 v의 방향이 되겠습니다. 

 

왼손 좌표계도 있는데요, 오른손 좌표계와는 중지의 방향이 반대가 된다는 점만 다릅니다.

 

 

 

(6) 길이와 싸인함수를 이용한 벡터곱 구하기 (vector product calculation with length and a sine function)

 

내적(inner product)을 계산할 때는 길이(length)와 코사인(cosine)을 사용해서 구하는데요, 벡터곱(vector product)은 벡터의 길이(length)와 싸인(sine) 함수를 이용해서 구할 수 있습니다.  (증명은 생략합니다)

 

 

 

 

(7) 두 벡터로 이루어진 평행사변형의 넓이 계산 (calculation of the area of the parallelogram spanned by vector a and b)

 

두 벡터 a와 b의 벡터곱(vector product, cross product)은 두 벡터로 이루어진 평행사변형의 넓이와 같다고 하였습니다.  두 벡터 a와 b로 이루어진 평행사변형의 넓이를 구해보면 (6)번에서 제시한 두 벡터의 벡터곱 공식과 일치함을 알 수 있습니다.  두 벡터로 이루어진 평행사변형의 넓이를 구하고 싶으면 두 벡터의 벡터곱을 구하면 되겠습니다.

 

 

 

 

 

 

(8) 벡터곱의 성질 (properties of vector product)

 

벡터곱은 내적과 같은 성질도 있고 다른 성질도 있습니다.  임의의 실수와의 곱은 순서에 상관없이 모두 동일하다는 점과 분배법칙(distributive law)을 만족한다는 점은 내적과 벡터곱이 동일합니다. 

 

반면에 내적은 교환법칙(commutative law)이 성립하지만, 벡터곱은 교환법칙이 성립하지 않는다(anti-commutative)는 점에서 차이가 있습니다.  그리고 벡터곱은 결합법칙도 일반적으로 성립하지 않는다(not associative)는 점 때문에 괄호를 생략하면 안됩니다. 내적은 결과가 scalar 이지만 벡터곱은 결과가 vector이므로 서로 다른 성질을 가지게 되는 것입니다.  

 

 

 

 

(9) 벡터곱의 최대, 최소 (max, min of vector product)

 

(6)번에서 벡터곱을 구하는 공식이 v = |a|*|b|*sin(θ)n 이라고 하였는데요, 이 공식에서 두 벡터가 수직(angle between a and b = 90 degree)일 때 벡터곱이 최대(outer product is max), 두 벡터가 평행일 때(angle between a and b = 0 degree) 벡터곱이 최소(outer product is min)임을 유추할 수 있습니다.

 

 

 

(10) 외적 (outer product)

 

위에서 소개한 두 벡터의 벡터곱(vector product, cross product)의 결과는 벡터인 반면에, 두 벡터의 외적(outer product)의 결과는 행렬입니다. 두 벡터의 외적(outper product)은 아래와 같이 계산합니다. 

 

 

 

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

 

행렬, 벡터 관련 포스팅은 아래 링크를 걸어놓았습니다.

 

행렬 기본 이해

특수한 형태의 행렬

가우스 소거법을 활용한 역행렬 계산

행렬의 기본 연산 (+, -, *, /, ^, %*%, colMeans(), rowMeans(), colSums(), rowSums()) 

벡터의 기본 이해와 연산 (vector: addition, subtraction, multiplication by scalar)

벡터의 곱 (1) 내적 (inner product, dot product, scalar product, projection product)

 

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

 

728x90
반응형
Posted by Rfriend
,

지난번 포스팅에서는 벡터의 기본 개념과 벡터의 합, 차, 스칼라배에 대해서 알아보았습니다.


이번 포스팅에서는 2가지의 벡터의 곱중에서 먼저 내적(inner product, dot product, scalar product,  projection product)을 소개하고, 다음번 포스팅에서 외적(outer product, cross product, vector product, directed area product)에 대해서 다루도록 하겠습니다.



[ 벡터 곱 2가지 종류 (2 types of Vector Multiplication) ]



내적(inner product, dot product)과 외적(outer product, cross product)을 비교해보면 아래 표와 같은데요, 처음에 보면 무슨 뜻인가 이해가 안갈 수도 있겠습니다. 내적과 외적의 설명을 다 읽어보시고 마지막으로 종합해서 다시 한번 정리하는데 활용하면 좋겠습니다.



[ 벡터의 내적과 외적 비교 ]

(comparison between inner(or dot) product and outer(or cross) product of vector)






이제 내적(inner product)에 대해서 하나씩 설명해보도록 하겠습니다.



(1) 내적의 표기 (notation and symbol of the inner product)


두 벡터의 내적(inner product)은 아래 그림처럼 「.」(dot)으로 표기하며, 이래서 점곱(dot product)이라고도 말합니다.  혹은 (a, b)와 같이 표기하기도 합니다.  결과값이 스칼라이기 때문에 스칼라곱(scalar product)이라고도 하며, 계산할 때 한쪽 벡터의 코사인값을 사용하기 때문에 (즉, 한쪽 벡터에 직사광선을 쪼였을 때 그 그림자에 해당하는 코사인값을 사용) 영사곱(projection product)이라고도 말합니다.


똑같은 개념을 두고 왜 이리 표현하는 말들이 많은지 의아할 수도 있겠는데요, 대수학, 기하학, 물리학 등의 학문영역별로 명칭, 표기가 다르다는 정도만 이해하면 되겠습니다.  최적화에서도 민감도분석할 때 보면 수학자는 쌍대변수(dual variable)이라고 말하는데 경제학자들은 잠재가격(shadow price)라고 말하거든요.  헛갈리는데 다 같은 말입니다. ^^;







(2) 내적의 정의 (difinition of the inner product)


R^n 내의 두 열 벡터 a, b에 대하여 곱 T(a)b 의 결과인 단일 성분을 갖는 1 * 1 행렬, 즉 하나의 실수인 Scalar 가 내적(inner product)이 되겠습니다.  그 수식을 풀어써보면 아래와 같은 계산식이 되며, 그 output은 스칼라(Scalar)가 됩니다. 


참고로, 외적(outer product)은 output이 벡터(Vector)가 됩니다. 




아래에 두개의 성분(2차원, 2 dimension)을 가지는 열벡터 a=(-5, 6), b=(3, 9)의 내적 예와 세 개의 성분(3차원, 3 dimensions)을 가지는 열벡터 c=(5, 3, 6), d=(2, 7, 4)에 대한 내적 계산을 소개하였습니다.  같은 행의 component끼리 각각 곱해서 모두 더하면 됩니다.







위의 2개의 문제를 R의 '%*%' 함수를 사용해서 풀어보면 아래와 같습니다. 

위에서 소개한 공식을 가지고 아래에 사용자정의 함수도 한번 만들어봤습니다.  R에 내적계산을 위한 함수로 '%*%'가 있기 때문에 굳이 사용자정의함수를 사용할 필요는 없겠습니다만, 개념을 이해하는 차원에서 참고하시기 바랍니다.



> ##--------------------------------------
> ## multiplying a vector by a vector
> ##--------------------------------------
> 
> 
> ##---------
> ## (1) dot product
> 
> ## vector with 2 components (dimensions)
> a <- c(-5, 6)
> b <- c(3, 9)
> 
> # dot product of vector with 2 components (dimensions) : (a) %*%
> a %*% b
     [,1]
[1,]   39
> 
> 
> # dot product of vector with 2 components : (b) user defined function
> dot_prod_fun_v2 <- function(a, b) {
+   if(length(a)!=2 | length(b) !=2) stop('number of vector component is not 2')
+   d <- a[1]*b[1] + a[2]*b[2]
+   return(d)
+ }
> 
> dot_prod_fun_v2(a=a, b=b)
[1] 39
> 
> 
> 
> ## vector with 3 components (dimensions)
> c <- c(5, 3, 6)
> d <- c(2, 7, 4)
> 
> # dot product of vector with 3 components (dimensions) : (a) %*%
> c %*% d
     [,1]
[1,]   55
> 
> 
> # dot prduct of vector with 3 components : (b) user defined function
> dot_prod_fun_v3 <- function(c, d) {
+   if(length(c)!=3 | length(d) !=3) stop('number of vector component is not 3')
+   dot_prd <- c[1]*d[1] + c[2]*d[2] + c[3]*d[3]
+   return(dot_prd)
+ }
> dot_prod_fun_v3(c=c, d=d)
[1] 55
 




(3) 내적의 성질 (properties of the inner product)


수학자들이 정의하는 실내적공간(real inner product space, or real pre-Hilbert space)의 정의와 공리는 아래와 같습니다.  실내적의 공리로 교환법칙(commutative law), 임의의 실수 c곱의 자유로운 이동 가능, 분배법칙(distributive law) 등의 공리도 아래에 소개하였습니다.





(4) 내적의 계산 원리, 방법 1 (1st formula of the inner product calculation)


내적을 계산하는 원리, 방법중에 벡터를 성분분해해서 각 성분들의 벡터의 길이(length of vector, norm)를 가지고 곱한 후 더하는 방법으로 구하는 방법이 있습니다.  아래 그림에 벡터 a를 ax, ay로, 벡터 b를 bx, by로 분해한 후에 내적을 구하는 방법을 소개해 보겠습니다. 힘과 방향을 가지는 벡터를 분해할 수 있다는 것은 벡터 연산을 할 때 굉장히 중요한 개념입니다. 참고로, 벡터와 스칼라를 곱했을 때도 분해한 벡터 성분에 스칼라를 각각 구해서 구하게 됩니다.






(5) 내적의 계산 원리, 방법 2 (2nd formula of the inner product calculation)


내적을 계산하는 또 한가지 방법은 벡터의 힘의 크기 또는 길이(magnitude or length of vector, norm)와 각도(angle between vector a and b)를 이용하는 방법입니다.  벡터의 힘의 크기 또는 길이는 "norm" 이라고도 불립니다.  두 개중 한개의 벡터에 빛을 비추었을 때 직각으로 생기는 그림자 (=vector a * cosine(θ))에다가 나머지 다른 한개의 벡터를 곱하는 개념입니다.





위의 내적 구하는 공식에 cos(θ)가 사용이 되었는데요, 참고로 직각삼각형 ABC의 삼각함수(trigonometric functions) sine, cosine, tangent 구하는 공식은 아래와 같습니다. 





참고로 벡터의 힘의 크기 또는 길이(magnitude or length of vector), 또는 다른 말로 "norm" |a|, |b|를 구하는 방법은 아래와 같습니다. 





(6) 내적을 활용한 두 벡터의 각도 계산 (calculating the angle between vector a and b)


위에서 소개한 두 벡터의 내적을 구하는 공식을 사용하면 벡터의 길이(length of vector)를 구하거나 혹은 두 벡터간 각도(angle between vector a and b)를 구할 수 있습니다.  왜 내적을 공부해야 하지, 내적을 어디에 써먹을 수 있지 궁금하셨을 것 같은데요, 위에서 예로 들었던 두 벡터 a=(-5, 6), b=(3, 9)의 각도를 내적을 활용해서 구해보도록 하겠습니다.



참고로, 위 계산 절차의 제일 마지막에 cos^-1(0.526354)*57.3 을 했는데요, inverse(cos(0.526354))를 통해서 계산된 값이 degree 가 아니라 radian 이기 때문에 1 radian 은 약 57.3 이므로 이를 곱해준 것입니다.  degree는 우리가 일반적으로 사용하는 것처럼 원을 0~360도 표기하는 방법이구요, radian은 부채꼴의 호의 길이와 반지름의 길이가 같게 되는 각도를 1 radian이라고 합니다.
180 degree = π radian 이며, 1 radian = 180 degree/ π = 57.3 입니다.

이를 R을 사용해서 계산해보면 아래와 같습니다.  사용자정의함수로 작성했습니다. 참고로, 함수 acos()는 cos()의 inverse 함수입니다.

> # angle between vector a and b
> a <- c(-5, 6)
> b <- c(3, 9)
> 
> angle_theta <- function(a, b){
+   dot.prod <- a%*%b 
+   norm.a <- norm(a, type="2")
+   norm.b <- norm(b, type="2")
+   theta_radian <- acos(dot.prod / (norm.a * norm.b))
+   angle_theta <- 57.3*theta_radian
+   as.numeric(angle_theta)
+   
+   return(angle_theta)
+ }
> 
> angle_theta(a, b)
         [,1]
[1,] 58.24481

 



위의 예에서는 이해를 돕기 위해서 2차원 (구성요소가 2개) 벡터 a, b를 가지고만 설명을 했는데요, 내적은 실벡터공간 내 3차원, 4차원, ..., n차원 벡터 모두에 대해서 가능합니다.  반면 외적은 3차원 유클리디안 공간에서만 가능합니다.


다음 번에는 벡터의 곱 두번째로 외적 (outer product, cross product, vector product, tensor product) 에 대해서 소개하도록 하겠습니다.

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

행렬, 벡터 관련 포스팅은 아래 링크를 걸어놓았습니다.

 

행렬 기본 이해

특수한 형태의 행렬

가우스 소거법을 활용한 역행렬 계산

행렬의 기본 연산 (+, -, *, /, ^, %*%, colMeans(), rowMeans(), colSums(), rowSums()) 

벡터의 기본 이해와 연산 (vector: addition, subtraction, multiplication by scalar)

벡터의 곱 (2) 외적 (outer product, cross product, vector product, tensor product)

 

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

 





728x90
반응형
Posted by Rfriend
,