티스토리 뷰

일반적으로 데이터를 가공하지 않은 상태로 막대그래프를 그리면, 아래와 같이 뒤죽박죽 나오게 된다. 보는데 문제는 없지만, 그래프를 딱 봤을때, 최소/최대값이 무엇인지 눈으로 비교하면서 찾아야 하는 불편함이 있다.


아래 처럼 막대그래프를 정렬하면, 어느값이 가장 높은지 낮은지 비교하며 찾을 필요없이 가장 우측 혹은 좌측을 주시하게 되면서 훨씬 이해하기 쉬운 그래프가 된다.


정렬의 기술을 알기전에, 우선 샘플 데이터를 하나 가져온다. tidytuesday 데이터를 하나 가져다 쓴다. 데이터의 설명은 여기를 클릭해서 참고 바란다.

library(patchwork)
library(tidyverse)
pride_aggregates <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022-06-07/pride_aggregates.csv')


첫번째 방법은 그래프를 그리기 전에 데이터에서 x 축의 값 필드를 factor 로 지정하여 정렬하는 것이다. 아래보면, fct_reorder 라는 함수가 그 역할을 하고, 내림차순을 하고 싶으면, .desc 를 TRUE 로 지정하면 된다. company 필드를 total_contributed 의 숫자를 기준으로 정렬하겠다는 의미이다. 아래 그래프처럼 그려진다고 보면 된다.

pride = pride_aggregates %>% 
  janitor::clean_names() %>% 
  filter(company != 'Grand Total') %>% 
  mutate(company = fct_reorder(company, total_contributed, .desc = T)) %>%
  mutate(max_yn = max(total_contributed) == total_contributed) %>% 
  mutate(total = round(total_contributed / 1000, 1)) %>%
  head()


두번째 방법은 ggplot 그래프 그릴때 x축에 reorder 함수를 써서 정렬하는 방식이다. 이렇게 되면 오름차순으로 정렬이 될텐데, 만약 내림차순으로 하고 싶으면 total_contributed 에 - 마이너스 기호를 붙이면 된다.

ggplot(pride, aes(x = reorder(company, total_contributed), y = total_contributed, fill = max_yn)) + 
  geom_col(width = 0.7) + 
  geom_text(aes(x = company, y = total_contributed, label = total), 
            vjust = -0.7, colour = "gray30", size = 4,
            family = "AppleSDGothicNeo-ExtraBold") +
  scale_y_continuous(expand = expansion(c(0, 0.05)), 
                     limits = c(0, max(pride$total_contributed) * 1.1)) +
  scale_fill_manual(values = c("#F77E21", "#D61C4E")) +
  theme_void(base_family = "AppleSDGothicNeo-ExtraBold") + 
  theme(
    plot.margin = margin(1,1,1,1, "cm"),
    legend.position = "none",
    axis.text.x = element_text(margin = margin(3,0,0,0, "mm"),
                               colour = "gray30", size = 11)
  )
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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 31
글 보관함