이번 시간에는 ggplot에서 그래프들을 facet하는 것에 대해 공부해보겠다.
우선 facet이 무엇인지 알기 위해 코드부터 실행해보자.
1. facet_wrap()
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
facet_wrap(~class)
![]() |
![]() |
첫 번째 결과는 facet_wrap(~class)을 실행하지 않은 결과
두 번째 결과는 facet_wrap(~class)을 추가한 결과이다. 우측의 결과를 확대하여 어떤 변화가 적용된건지 확인해보자.
x축과 y축이 각각 dsipl, hwy인 것은 고정이나 class에 value별로 plot이 나뉘어 시각화된 것을 확인할 수 있다.
1. What happens if you try to facet by a continuous variable like hwy? What about cyl? What’s the key difference?
연속형 변수를 가지고 facet을 하면 어떻게 될까? 범주형으로 했을 때는?
직접 코딩하여 확인해보자.
ggplot(mpg, aes(displ, cty)) +
geom_point()
facet_wrap(~hwy)
연속형 변수인 hwy에 의해 facet을 실행한 경우 연속형 변수를 범주화하여 각각의 값으로 facet된 plot들이 나타난다. 중간 중간 존재하지 않은 value에 대해서는 facet되지 않았다. 즉 빈 cell은 존재하지 않는다.
2. Use faceting to explore the 3-way relationship between fuel economy, engine size, and number of cylinders. How does faceting by number of cylinders change your assessement of the relationship between engine size and fuel economy?
facet을 사용해서 연비와 엔진크기, 실린더의 수 사이에 관계를 알아보자. cyl 값을 기준으로 facet해서 엔진사이즈와 연비 사이의 관계가 어떻게 변화하는지 확인해보자.
ggplot(mpg, aes(displ, hwy)) +
geom_point()
우선 cly별로 facet을 하지 않았을 때는 단순히 displ이 낮으면 연비가 좋을 확률이 높다 정도의 평가가 가능하다.
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
facet_wrap(~cyl)
하지만 cyl별로 facet하여 plot을 시각화하면 추가적인 정보를 얻을 수 있다.
2. Facet's argument 'scaling '
facet_wrap()의 옵션인 scales가 무엇이고 언제 이것을 사용할 수 있을지 알아보자.
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
facet_wrap(~class, scales='free')
scales = 'free'로 두면 각 facet된 plot에 위치하는 variables들의 범주에 따라 범례가 바뀐다.
scales의 default값은 fixed이다. fixed로 두면 모든 facet의 스케일이 동일해진다.
당장 보기에는 fixed가 편하지만, free로 보아야 하는 경우도 분명 있으니 기억해두자.
'R > Exploratory data analysis' 카테고리의 다른 글
ggplot2::geom fuctions (0) | 2023.04.24 |
---|---|
ggplot2:: geom_graphs (0) | 2023.04.24 |
ggplot2:: geom_smooth() (0) | 2023.04.06 |
ggplot2::aesthetic mapping (0) | 2023.04.05 |
1. R program on mac (0) | 2023.03.10 |