티스토리 뷰

ggplot2 에서 facet 을 이용하면 단순히 하나의 plot 이 아니라, 제3의 값에 따라 x/y 축의 상관관계를 한눈에 볼 수 있다. facet 를 사용하면 상단과 우측에 facet 기준정보를 볼 수 있다. 이번 포스팅은 우측에 있는 facet 기준정보를 오른편에서 왼편으로 옮겨보는 일을 해보려 한다.

가장 단순하게 만든 facet 그래프이다.  week (주) 와 wday(요일) 정보를 기준으로 시간대별 지하철 하차인원의 histogram 그래프를 그려본다. 역시나 별다른 셋팅을 하지 않으면 디폴트는 상단과 우측에 정보가 표시된다.

ggplot(subway2,aes(x = times)) +
  geom_histogram(aes(fill = ..count..), alpha = 1, binwidth = 6) +
  facet_grid(week ~ wday) +
  theme(legend.position = "none")

 

여기에서 facet_grid 내에 switch = "y" 를 입력하면 오른편에 있던 정보가 왼편으로 이동한다.

ggplot(subway2,aes(x = times)) +
  geom_histogram(aes(fill = ..count..), alpha = 1, binwidth = 6) +
  facet_grid(week ~ wday, switch = "y") +
  theme(legend.position = "none")

 

 

하지만 내가 원하는 건, 그래프 바깥쪽으로 꺼내는 것이였고, theme 에서 strip.placement = "outside" 를 설정하면 아까 18~22주로 표시되던 facet 정보가 바깥쪽으로 나오는 것을 볼 수 있다.

ggplot(subway2,aes(x = times)) +
  geom_histogram(aes(fill = ..count..), alpha = 1, binwidth = 6) +
  facet_grid(week ~ wday, switch = "y") +
  theme(legend.position = "none",
        strip.placement = "outside")

반응형

하지만, y 축 정보와 facet 정보가 같이 있다보니, y 축 정보를 반대편인 오른편으로 옮겨보기로 한다. scale_y_continuous(position = "right") 를 추가한다.

ggplot(subway2,aes(x = times)) +
  geom_histogram(aes(fill = ..count..), alpha = 1, binwidth = 6) +
  scale_y_continuous(position = "right") +
  facet_grid(week ~ wday, switch = "y") +
  theme(legend.position = "none",
        strip.placement = "outside")

 

거의 다 된 듯 한데, facet 왼편 숫자가 누워있다보니 똑바로 돌려보기로 한다. 테마에 strip.text.y.left = element_text(angle = 0) 를 추가한다. 만약 facet 를 왼편으로 옮긴게 아니었다면 left 를 제거한 strip.text.y = element_text(angle = 0)로 입력하면 된다.

ggplot(subway2,aes(x = times)) +
  geom_histogram(aes(fill = ..count..), alpha = 1, binwidth = 6) +
  scale_y_continuous(position = "right") +
  facet_grid(week ~ wday, switch = "y") +
  theme(legend.position = "none",
        strip.placement = "outside",
        strip.text.y.left = element_text(angle = 0))

 

디자인을 어느정도 수정하면 아래와 같이 facet 정보의 위치를 변경하기 전과 후로 비교해 볼 수 있다.

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
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
글 보관함