티스토리 뷰

그래프를 그릴때 x, y 축만 설정해서 데이터를 시각화 할 수도 있지만, 어떤 특정 필드를 기준으로 그룹(group)을 만들어서 표현하게 된다. 예를 들어 특정 데이터값을 바탕으로 그룹 막대그래프를 그룹핑하면 아래와 같은데, 이때 z 로 표시된 그룹정보 범례(legend)라 불리는 영역이 생성된다.

library(tidyverse)

set.seed(3)
tb = tibble(y = sample(30:100, 8)) %>% 
  arrange(y) %>% 
  mutate(x = rep(1:4, each = 2), z = rep(c("1", "2"), 4))
  
ggplot(tb, aes(x, y, fill = z)) + 
  geom_col(position = "dodge", width = 0.7) + 
  coord_flip()

 

범례 이름 변경하기

위의 그래프를 보면 범례가 그냥 1, 2 이런식으로 되어 있는데, 이걸 매핑해서 이름변경을 할 수가 있다. scale_fill_maunal 로 labels 를 지정하면 된다. 지정하는 김에 색도 지정해본다.

ggplot(tb, aes(x, y, fill = z)) + 
  geom_col(position = "dodge", width = 0.7) + 
  scale_fill_manual(values = c("#365384", "#A8CBDC"), 
                    breaks = c("2", "1"),
                    labels = c("Tiger", "Lion")) +
  coord_flip()

반응형

범례의 위치 변경

범례는 그래프의 오른편에 디폴트로 나오게 되는데, 이 범례의 위치도 조정이 가능하다. theme 함수안에 legend.position 의 값을 지정하면 되는데, ["none", "left", "right", "bottom", "top"] 값 중에 하나를 지정하면 된다. 4개의 위치를 각각 실행하면 아래 그림들과 같이 나오게 된다.

ggplot(tb, aes(x, y, fill = z)) + 
  geom_col(position = "dodge", width = 0.7) + 
  scale_fill_manual(values = c("#365384", "#A8CBDC"), 
                    breaks = c("2", "1"),
                    labels = c("Tiger", "Lion")) +
  coord_flip() +
  theme_minimal() +
  theme(legend.position = "left")

 

저렇게 딱정해진 위치말고, 원하는 위치가 있으면 좌표처럼 지정도 가능하다. legend.position = c(0.88, 1.12) 와 같이 2개의 숫자를 입력하면되고, 0~1 이 그래프의 끝과 끝이라 보면 된다. 그 범위를 넘어서는것은 조금씩 0.1 씩 증가하면서 확인해보면 된다.

ggplot(tb, aes(x, y, fill = z)) + 
  geom_col(position = "dodge", width = 0.7) + 
  scale_fill_manual(values = c("#365384", "#A8CBDC"), 
                    breaks = c("2", "1"),
                    labels = c("A타입", "B타입")) +
  coord_flip() +
  scale_x_continuous(breaks = 4:1,
                     labels = c('가', '나', '다', '라'))+
  theme_minimal(base_family = "AppleSDGothicNeo-ExtraBold", base_size = 13)
  theme(
    axis.title = element_blank(),
    axis.text.y = element_text(size = 14),
    plot.margin = margin(2,1.5,0.8,1, unit = "cm"),
    legend.position = c(0.88, 1.12),
    legend.direction = "horizontal",
    legend.title = element_blank(),
    legend.text = element_text(family = "AppleSDGothicNeo-SemiBold",
                               margin = margin(0,3,0,-1, unit = "mm")),
    legend.key.width = unit(1, "cm"),
    panel.grid = element_blank(),
    panel.grid.major.x = element_line(colour = c("#bdbdbd"), size = 0.3)
  )
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
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
글 보관함