본문 바로가기
R

R - plotly: ggplot2 패키지 (2)

by IT두잇 2022. 3. 17.

ggplot2 패키지를 활용한 그래프에 대해 조금 더 자세히 알아보겠습니다. 😊

 

산점도 그래프: facet_grid( )

facet_grid( )를 사용하면 x축의 그래프 별로 그룹지어 그래프를 그릴 수 있습니다.

# 세로로 그루핑: facet_grid ( ~ 변수)
ggplot(data = mpg, aes(x=displ, y = hwy, color = drv, shape = drv))+
  geom_point(size=3)+
  facet_grid( ~ drv)

# 가로로 그루핑: facet_grid ( 변수 ~.)
ggplot(data = mpg, aes(x=displ, y = hwy, color = drv, shape = drv))+
  geom_point(size=3)+
  facet_grid( drv~ .)

 


산점도 그래프: facet_wrap( )

그룹의 개수가 많을 경우, facet_grid( )보다 facet_wrap( )가 효율적인 배치를 적용합니다.

ggplot(data = mpg, aes(x=displ, y = hwy, color = drv, shape = drv))+
  geom_point(size=3)+
  facet_wrap( ~ class)


산점도 그래프: (position = 'jitter')

jitter은 산점도 그래프에 흩어지는 기능을 추가합니다.

# jitter 설정 추가
ggplot(data = mpg, aes(x=displ, y = hwy, color = drv))+
  geom_point(size=3, position= 'jitter')

# jitter의 크기 설정
ggplot(data = mpg, aes(x=displ, y = hwy, color = drv))+
  geom_point(size=3)+
  geom_jitter(width = 0.9, height = 0.5)

 

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

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

jitter 효과 적용 후:                                                             jitter 효과 크기 설정 후:

 

 


라인 그래프:

geom_line( )은 라인 그래프를 그릴 때 사용합니다.

ggplot(data = mpg, aes(x=displ, y = hwy, color = drv)) +
  geom_line()


변수 형식 바꾸기: as.factor / as.integer

바 그래프를 특정 변수로 색칠할 때, 수치형(integer) 변수로는 색칠되지 않는 것을 볼 수 있습니다.

# factor(범주형) 변수로 설정
ggplot(data = mpg, aes(x=displ, fill = class)) + geom_bar()

# int(수치형) 변수로 설정 -> 설정되지 않음
ggplot(data = mpg, aes(x=displ, fill = cty)) + geom_bar()

 

따라서 수치형 변수를 범주형 변수로 변환하는 과정이 필요합니다.

이럴때는 as.factor( ) 함수를 활용하면 됩니다.

# factor로 변환한 cty 변수를 다시 cty변수에 덮어씌워줍니다.
mpg$cty <- as.factor(mpg$cty)

# 범주형으로 변환한 cty로 다시 바 그래프를 색칠합니다. 
ggplot(data = mpg, aes(x=displ, fill = cty)) + geom_bar()

 

다시 변수를 수치형(integer)로 변환하고 싶을 경우, as.integer( ) 함수를 이용합니다.

# integer로 다시 변환한 cty 변수를 cty변수에 덮어씌워줍니다.
mpg$cty <- as.integer(mpg$cty)

 

변수 형식를 바꾸어 저장하지 않고, 그래프를 그릴 때만 형식을 변경할 수도 있습니다.

## ggplot 안에서 factor로 바꿈 (데이터 자체를 바꾸지 않고)
ggplot(data = mpg, aes(x=displ, fill = as.factor(cty))) + geom_bar()