티스토리 뷰

막대그래프를 그리다보면, 음수/양수가 혼재된 막대그래프를 그려야 할 때가 있다. 막대그래프위에 숫자표기를 해서 수치를 강조해볼까 한다. 그리고 마지막에 약간의 디자인을 조정해서 오른쪽처럼 변경해볼까 한다.

 

#tidytuesday 데이터 일부를 가져와서 활용하고자 한다. industry 를 그룹핑해서 랭킹 상승/하락의 sum 을 구해서 22년과 21년대비 어느산업이 더 순위가 상승했는지 알아보는 차트를 만들어보고자 한다.

poll <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022-05-31/poll.csv')
poll_industry = poll %>% 
  filter(year == 2021) %>% 
  group_by(industry) %>% 
  summarise(n_total = sum(replace_na(change,0))) %>% 
  filter(n_total != 0) %>% 
  mutate(pos = n_total >= 0) %>% 
  mutate(hjust = ifelse(pos, -0.7, 1.5)) 
  
  # A tibble: 16 × 4
   industry           n_total pos   hjust
   <chr>                <dbl> <lgl> <dbl>
 1 Automotive              19 TRUE   -0.7
 2 Consumer Goods         -62 FALSE   1.5
 3 Ecommerce              -15 FALSE   1.5
 4 Energy                  -5 FALSE   1.5
 5 Financial Services     -21 FALSE   1.5
 6 Food & Beverage         14 TRUE   -0.7
 7 Food Delivery           -2 FALSE   1.5
 8 Groceries               17 TRUE   -0.7
 9 Industrial              18 TRUE   -0.7
10 Logistics               -4 FALSE   1.5
11 Media                  -18 FALSE   1.5
12 Other                   13 TRUE   -0.7
13 Pharma                 -37 FALSE   1.5
14 Retail                  54 TRUE   -0.7
15 Tech                   121 TRUE   -0.7
16 Telecom                -62 FALSE   1.5
반응형

기본적인 형태만 만들어본다. reorder 로 올림차순으로 정렬하고, 수치를 막대그래프 위에 추가하고, 음수/양수를 구분지어 색을 넣어준다. 마지막으로 coord_flip 으로 수평 막대그래프를 만든다. 

ggplot(poll_industry, aes(reorder(industry, n_total), n_total, fill = pos)) +
  geom_col() +
  geom_text(aes(x = industry, y = n_total, label = n_total), 
            hjust = poll_industry$hjust, colour = "gray30", size = 4) +
  coord_flip() +
  scale_y_continuous(limits = c(-100, 140))

 

디자인을 변경하여 마무리 한다. 특히 신경쓴건, 숫자를 위에 표시할때, hjust 로 하나의 수치로 되지 않았다. 양수는 더 오른쪽에, 음수는 더 왼쪽에 위치해야 하다보니, 데이터를 가공할때 hjust 라는 변수를 추가해서 먼저 정의해놓았다. 

ggplot(poll_industry, aes(reorder(industry, n_total), n_total, fill = pos)) +
  geom_col() +
  geom_text(aes(x = industry, y = n_total, label = n_total), 
            hjust = poll_industry$hjust, colour = "gray30", size = 4,
            family = "AppleSDGothicNeo-ExtraBold") +
  coord_flip() +
  scale_y_continuous(limits = c(-100, 140)) +
  scale_fill_manual(values = c("#ED6663", "#4E89AE")) +
  theme_void(base_family = "AppleSDGothicNeo-Bold") +
  theme(
    plot.margin = margin(1,1,1,1, "cm"),
    legend.position = "none",
    axis.text.y = element_text(hjust = 1, colour = "gray30")
  )
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
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
글 보관함