본문 바로가기
R

R - plotly: ggplot2 패키지 (1)

by IT두잇 2022. 3. 17.

plotly는 인터랙티브한 그래프를 출력하는 라이브러리이며, Scala, R, Python 등에서 사용할 수 있습니다.

 

그래프 종류:

  • geom_point( ): 산점도
  • geom_bar( ): 바 그래프 (x변수)
  • geom_col( ): 바 그래프 (x변수 & y변수)
  • geom_histogram( ): 히스토그램
  • boxplot( ): 박스플롯

 

그래프 준비 과정:

1. 먼저 ggplot2 패키지를 사용하기 위해서는 패키지 설치 후, 로드가 필요합니다.

# ggplot2 패키지 설치하기
install.packages('ggplot2')

#library 로드하기
library(ggplot2)

 

2. 그래프를 그릴 데이터와 x축, y축을 설정합니다.

# ggplot(data = 데이터명, aes(x= x축 변수, y = y축 변수))
ggplot(data = mpg, aes(x= displ, y = hwy)) + geom_point()

 

3. 필요 시, x축과 y축의 범위를 지정합니다.

# xlim(x축 최소범위, x축 최대범위) + ylim(y축 최소범위, y축 최대범위)
ggplot(data = mpg, aes(x= displ, y = hwy)) +
   geom_point() + xlim(3,5) + ylim(10, 50) 

※ 여기서 geom_point( )는 산점도 그래프를 뜻합니다.

 

 

x축과 y축 외에 데이터로 컬러 혹은 모형을 설정할 수 있습니다.

# color 변수 설정
ggplot(data = mpg, aes(x= displ, y = hwy, color = cty)) +
   geom_point()

# shape 변수 설정
ggplot(data = mpg, aes(x= displ, y = hwy, shape = cty)) +
   geom_point()

컬러로 설정한 변수가 숫자형일 경우, 두번째 그래프와 같이 색의 농도로 나타납니다.

 


산점도 그래프

geom_point( )를 이용하여 산점도 그래프를 그릴 수 있습니다.

ggplot(data = mpg, aes(x = displ, y = cty)) +geom_point()


바 그래프

geom_bar( ) 그래프를 그릴 때는, x축 변수 하나만 설정합니다.

ggplot(data = mpg, aes(x = displ)) +geom_bar()

 

color = 변수 를 추가한 경우:                                            fill = 변수 를 추가한 경우:

 

 

geom_col( ) 그래프를 그릴 때는, x축과 y축 모두 설정 가능합니다.

ggplot(mpg, aes(x=class, y = hwy)) + geom_col()

 

position = ‘dodge’ : 그래프 바가 색깔 변수별로 나누어질 경우, 아래 두 종류로 그릴 수 있습니다.

# 왼쪽 그래프
ggplot(data = mpg, aes(x = drv, fill = fl)) + geom_bar()

# 오른쪽 그래프
ggplot(data = mpg, aes(x = drv, fill = fl)) + geom_bar(position = 'dodge')

 

position = ‘fill’ : 그래프가 y축을 가득채우도록 그래프를 수정할 수 있습니다.

ggplot(data = mpg, aes(x=displ, fill = as.factor(cty))) + geom_bar(position = 'fill')

 

 

+ 그래프 투명도/ 사이즈 / 모형 설정

# alpha: 투명도
# size: 크기
# shape: 모형
ggplot(mpg, aes(x=cty, y =hwy)) +geom_point(alpha =0.1, size = 3, shape = 22)

 


boxplot 그래프

ggplot(mpg, aes(x=class, y = hwy, fill=class)) + geom_boxplot()


히스토그램 그래프

geom_histogram으로 그래프를 그린 후,  추가 옵션을 작성해 바의 개수, 넓이과 색을 설정할 수 있습니다.

# binwith: 바의 넓이 설정
ggplot(mpg, aes(hwy)) + geom_histogram(binwidth = 5)

# bin: 바의 개수 설정
# color: 그래프 테두리 색 설정
# fill: 그래프 색 설정 
ggplot(mpg, aes(hwy)) +geom_histogram(bins = 18, color='white', fill='steelblue')


 

연속 변수로 그릴 수 있는 그래프 종류:

# geom_density()
ggplot(mpg, aes(hwy)) + geom_density()

# geom_area()
ggplot(mpg, aes(hwy)) + geom_area(stat = 'bin')

# geom_freqpoly() -  x축 변수 하나만 설정
ggplot(mpg, aes(hwy)) +geom_freqpoly()

geom_density( ) :                              geom_area( ) :                                geom_freqpoly( ) :