티스토리 뷰

ggplot2: 들어가기

  • package:ggplot2의 gg는 Grammar of Graphics의 약자이다. ggplot2는 Wilkinson 등(2005의 The grammar of Graphics라는 책의 내용을 바탕으로 Wickham이 만든 패키지이다. Wickham은 ggplot2를 소개하기 위해 책 ggplot2를 쓰기도 했다.
  • 시각화의 원리라고 할 수 있는 Grammar of Graphics는 자료 시각화의 핵심을 다음의 기본 3 요소로 정리하였다.
    • data : 무엇을 시각화할 것인가?
    • geom : 무엇으로 시각화할 것인가? 예) 점, 선, 막대 등
    • aesthetics : 어떤 시각적 특성(visual attributes)를 사용할 것인가?
      • 위치(xy), 크기(size), 모양(shape), 색깔(col), 농도(alpha) 등
      • 예를 들어 체중(data)을 점(geom)으로 시각화한다고 해보자. 체중은 위치로 나타낼 수도 있고, 크기로 나타낼 수도 있고, 농도로 나타낼 수도 있다. 여기서 체중과 같은 연속적 자료를 나타내기 적합한 시각적 특성이 있고, 그렇지 않은 시각적 특성이 있음을 유의하자. 예를 들어 체중을 모양으로 나타내기는 힘들 것이다.
      • 아래의 표는 측정 척도의 종류와 변환 가능한 시각적 특성을 나타낸다. 측정 척도의 종류에 맞는 시각적 특성을 선택하지 않을 경우 자료에 담기지 않은 정보를 시각화하게 될 우려가 있다.(참고)
      • 중요한 정보는 정확하게 인식할 수 있는 시각적 특성을 활용할 필요가 있다. 시각적 특성 인식의 정확성은 다음과 같다. 위치 > 길이 > 각도 > 면적 > 부피 > 색깔 > 밝기. 참고
측정 척도특징가능한 연산변환 가능한 시각적 특성
명목(Nominal)==!=사람이름, 나라이름색깔, 모양
서열(Ordianl)==!=><(상,중,하)
간격(Interval)임의적인 0==!=><+-날짜, 위치, 온도위치, 크기, 농도
비율(Ratio)==!=><+-*/체중, 절대온도위치, 크기, 농도
  • 여기서는 시각화 원리의 기본 3요소에 부수적 요인을 포함하여 다음의 7요소로 하였다.
    • 데이터(Data)
    • 기하학적 대상(Geoms)
    • 시각적 맵핑(Aesthetic mapping)
    • 보조선(Auxillary lines)
    • 좌표계(Coordinate System)
    • 범례(Legends)
    • 제목, 부제목, 설명, 테마(Title, subtitle, caption and themes)

시리즈 목차

  • 들어가기 & 시각적 맵핑 기본 소개
  • 기하학적 대상(Geoms)
  • 보조선(Auxillary lines)
  • 좌표계(Coordinate System)
  • 범례(Legends)
  • 제목, 부제목, 설명, 테마(Title, subtitle, caption and themes)
  • 총정리

시각적 맵핑(AESTHETIC MAPPING)

  • 여기서는 ggplot2 패키지의 데이터 mpg를 활용한다. 이 데이터는 미국에서 1999년에서 2008년까지 38종의 대중적인 자동차에 대해 연비 데이터를 가지고 있다. cty 컬럼은 city miles per gallon(도심에서 1 갤런 당 주행거리(마일))을 나타내고, hwy 컬럼은 highway miles per gallon(고속도록에서 1 갤런 당 주행거리(마일))을 나타낸다.
data(mpg, package='ggplot2')
  • 예를 들어 mpg의 displ(engine displacement=배기량)을 x-위치로, hwy을 y-위치로 변환해서 점(point)으로 시각화하고자 한다면 다음과 같이 쓸 수 있다.
ggplot(mpg, aes(x=displ, y=hwy)) + geom_point()

plot of chunk unnamed-chunk-2

  • 기본적인 산포도를 그리기 위해서는 다음과 같은 형식을 따른다. 여기서 data=는 시각화에 사용할 데이터를 결정하고, aes()는 Aesthetic mapping, 시각적 맵핑을 의미한다. aes() 안의 x=는 x-위치, y=는 y-위치, col=는 색깔, shape=은 모양을 나타내고, 데이터의 어떤 컬럼을 각 시각적 특성으로 나타낼 것인지를 결정한다. 마지막으로 geom_point()는 앞에서 결정한 시각적 특성을 점으로 시각화하겠다는 것을 나타낸다.
ggplot(data= , aes(x=  , y=   , col=  , size=  , shape=   )) + geom_point()
  • 두 개 이상의 기하학적 대상으로 시각화하는 경우(점과 선)
ggplot(data, aes(x=  , y=   , col=  , size=  , shape=   )) + 
  geom_point() + 
  geom_line()  
  • 점, 선, 그리고 데이터를 가장 잘 나타내는 선(geom_smooth)으로 데이터 시각화
ggplot(data, aes(x=  , y=   , col=  , size=  , shape=   )) + 
  geom_point() + 
  geom_line() +
  geom_smooth(method='lm/glm/gam/loess/MASS::rlm', span=  , formula=  )
  • 만약 x-위치를 결정하는 컬럼이 범주 데이터라면 한 위치에 여러 점이 찍힐 수 있다. 이럴 때에는 geom_jitter()을 사용하여 위치를 살짝 변경하거나, geom_boxplot() 또는 geom_violin()을 사용하여 분포로 표시할 수도 있다.
ggplot(mpg, aes(x=class, y=cty)) + geom_point() + 
  labs(title='자동차 연비(1999-2008)', caption='점이 겹친다')
ggplot(mpg, aes(x=class, y=cty)) + geom_jitter() + 
  labs(title='자동차 연비(1999-2008)', caption='geom_jitter()')
ggplot(mpg, aes(x=class, y=cty)) + geom_boxplot() + 
  labs(title='자동차 연비(1999-2008)', caption='geom_boxplot()')
ggplot(mpg, aes(x=class, y=cty)) + geom_violin() + 
  labs(title='자동차 연비(1999-2008)', caption='geom_violin()')
  • 연속 변수의 분포를 히스토그램(histograms)과 빈도폴리곤(frequency polygons)으로 나타내기
    • bins : 구획의 갯수
    • binwidth : 한 구획의 길이점
    • breaks : 구획의 시작점과 끝점
ggplot(data = , aes(x= )) + geom_histogram(bins=  , binwidth=  , breaks=  )
ggplot(data = , aes(x= )) + geom_freqpoly(bins=  , binwidth=  , breaks=  )  
ggplot(data = mpg, aes(x=cty)) + geom_histogram(bins= 30)
ggplot(data = mpg, aes(x=cty)) + geom_freqpoly(bins= 30)

plot of chunk unnamed-chunk-9plot of chunk unnamed-chunk-9

ggplot(data = mpg, aes(x=cty)) + geom_histogram(binwidth= 5)
ggplot(data = mpg, aes(x=cty)) + geom_freqpoly(binwidth= 5)  

plot of chunk unnamed-chunk-10plot of chunk unnamed-chunk-10

ggplot(data = mpg, aes(x=cty)) + geom_histogram(breaks= c(0,5,10,15:25,45))
ggplot(data = mpg, aes(x=cty)) + geom_freqpoly(breaks= c(0,5,10,15:25,45))  

plot of chunk unnamed-chunk-11plot of chunk unnamed-chunk-11

  • 범주 변수의 분포를 막대그림(bar chart)으로 나타내기
ggplot(data=mpg, aes(x=class)) + geom_bar(col='blue', fill='red')
#ggplot(data=mpg, aes(x=class)) + geom_bar(aes(col='blue', fill='red')) 라고 쓰지 않도록 조심하자.
#aes의 존재 유무에 따른 차이는 나중에 설명된다. 

plot of chunk unnamed-chunk-12

  • 다른 종류의 막대 그림 : 만약 분포 또는 빈도가 이미 하나의 변수(아래에서 df$n)로 저장되어 있다면 stat='identity'을 사용한다.
data(mpg, package='ggplot2')
dat <- table(mpg$manufacturer)
df <- as.data.frame(dat)
colnames(df) = c('name', 'n')
print(head(df))
##        name  n
## 1      audi 18
## 2 chevrolet 19
## 3     dodge 37
## 4      ford 25
## 5     honda  9
## 6   hyundai 14
ggplot(df, aes(x=name, y=n)) + geom_bar(stat='identity')

plot of chunk unnamed-chunk-13


참고자료


공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함