R(tidyverse) ggplot 1

Tae Yoon·2024년 4월 10일
0


ggplot 패키지 불러오기

library(ggplot2)

그래프 작성 템플릿

ggplot(data = <데이터>) + <지옴함수>(mapping = aes(<매핑모음>)

산점도 생성

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

ggplot(data=mpg)를 하면 빈 그래프 생성
mapping 인수는 변수들이 시각적 속성으로 어떻게 매핑될지 정의
mapping 인수는 ase()와 쌍을 이루는데 ase()의 x, y인수는 x, y축으로 매핑될 변수를 지정한다.

심미성 매핑

class 별로 색깔 구분

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy, color = class))

점의 크기로 구분

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy, size = class))

점의 투명도로 구분

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy, alpha = class))

점의 모양별로 구분

ggplot(data = mpg) +
  geom_point(mapping = aes(x = displ, y = hwy, shape = class))

ggplot2는 한번에 여섯개의 모양만 사용한다
ggplot2는 기본 셋팅값으로 나머지를 처리한다

심미성의 속성을 수동으로 설정할 수 있다

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy), color = "blue")

aes 괄호 밖에 쓰면 수동으로 설정 가능

stroke: 획두께 설정

ggplot(mpg)+geom_point(mapping=aes(x=displ, y=hwy, stroke=3))

color, fill

전체 컬러는 검정 안에 채우는 것은 하얀색

ggplot(mpg)+
  geom_point(mapping=aes(x=displ, y=hwy), shape=0, stroke=5, COLOR='black', fill='white', size=5)

컬러에 조건을 넣는, 변수도 가능

ggplot(mpg)+ geom_point(mapping= aes(x=displ, y=hwy, color=displ<6))

facet: 면분할

하나의 변수에 대해 면분할: facet_wrap()

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy)) +
  facet_wrap(~ class, nrow =2)

facet_wrap()은 이산형이어야 한다.
이산형 변수 : 값이 문자형이나 정수형처럼 서로 떨어져 있는 유형을 의미하며, 연속형과 대비되는 용어이다.
nrow: 지정할 행의 수, ncol: 저정할 열의 수

두 변수 조합으로 면분할: facet_grid()

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy)) +
  facet_grid(drv ~ cyl) 

열이나 행으로 면분할하고 싶지 않다면 변수 이름 대신 . 을 이용

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy)) +       
  facet_grid(. ~ cyl)

추세선 그래프: geom_smooth()

ggplot(mpg)+
  geom_smooth(mapping=aes(x=displ, y=hwy, linetype=drv))

linetype : 선의 타입을 변경 drv에 따라

산점도랑 추세선 합치기

ggplot에 매핑을 쓰는 것을 전역 매핑이라 한다
그전에 각각 geom함수에 매핑한건 로컬 매핑

ggplot(mpg, mapping=aes(x=displ, y=hwy))+
  geom_point(mapping= aes(color=drv))+
  geom_smooth(mapping=aes(linetype=drv))

범례를 보여주지 않는다 FALSE로 쓰는 것 유의하자

ggplot(mpg)+
  geom_smooth(mapping=aes(x=displ, y=hwy, color=drv), show.legend=FALSE)

변수에 따라 group

ggplot(data = mpg) + 
  geom_smooth(mapping = aes(x = displ, y = hwy, group = drv))

통계적 변환

막대그림: geom_bar()

ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut))

막대그림: 범주형 x축: 범주, y축: 도수 cut변수 커팅의 품질의 정도 범주형

막대그림을 stat을 이용해서 도수를 계산하는 방법 기존의 결과와 동일

ggplot(diamonds)+
  stat_count(mapping=aes(x=cut))

stat(prop): 상대도수

ggplot(diamonds)+
  geom_bar(mapping=aes(x=cut, y=stat(prop), group=1))

group을 지정하지 않으면 다 똑같이 나온다

ggplot(diamonds)+
  geom_bar(mapping=aes(x=cut, y=stat(prop)))

y축이 그래프 끝까지 채운다

demo <- tribble( ~cut, ~freq, “Fair”, 1610, “Good”, 4906, “Very Good”, 12082, “Premium”, 13791, “Ideal”, 21551 )

ggplot(data = demo) + geom_bar(mapping = aes(x = cut, y = freq), stat = “identity”)

원래 데이터값을(freq) 사용하려면 aes 바깥에 stat='identity'를 지정해야 실행

stat_summary: x와 y값에 대한 요약값을 알 수 있다

ggplot(diamonds)+
  stat_summary(
    mapping=aes(x=cut, y=depth),
    fun.min=min,
    fun.max=max,
    fun=median)

위치 조정

막대그래프에 색상을 입힐 때 color 또는 fill

ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut, color = cut))

color는 막대의 테두리에 색깔을 입힌다

ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut, fill = cut))
  
ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut, fill = clarity))

fill은 막대 내부에 색깔을 입힌다

ggplot(data = diamonds, mapping = aes(x = cut, fill = clarity)) + 
 geom_bar(alpha = 1/5, position = "identity")

position = "identity"는 위치 조정을 적용하지 않고 그래프를 겹쳐 그린다

ggplot(data = diamonds) +
 geom_bar(
 mapping = aes(x = cut, fill = clarity), position = "fill")

position = “fill” 은 누적 막대들이 동일한 높이가 되어 그룹들 사이의 비율을 비교하기 쉬워진다

ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut, fill = clarity), position = "dodge")

position = “dodge”를 하면 겹치는 객체가 서로 옆에 배치

ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy), position = "jitter")\

position = “jitter”를 하면 랜덤 노이즈가 추가되어 어느 두 점도 같은 양의 랜덤 노이즈를 받을 가능성이 없기 때문에 포인트가 퍼지게 된다.

좌표계

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

상자그림 그래프: geom_boxplot()

ggplot(data = mpg, mapping = aes(x = class, y = hwy)) + 
  geom_boxplot() +
  coord_flip()

coord_flip()은 x와 y축을 바꾼다

bar <- ggplot(data = diamonds) + 
 geom_bar(
 mapping = aes(x = cut, fill = cut), 
 show.legend = FALSE,
 width = 1) + 
 theme(aspect.ratio = 1) +
 labs(x = NULL, y = NULL)
 bar + coord_flip()

bar + coord_polar()

coord_polar()는 극좌표를 사용한다. 극좌표를 사용하면 막대 그래프와 Coxcomb차트 사이의 흥미로운 관계를 볼 수 있다

그래프 레이어 문법

ggplot(data = <데이터>) + 
   <지옴 함수>(
     mapping = aes(<매핑모음>),
    stat = <스탯>, 
    position = <위치>
    ) +
   <좌표계 함수> +
   <면분할 함수>

0개의 댓글

관련 채용 정보