티스토리 뷰

반응형

막대그래프를 ggplot 으로 막대그래프를 표현하다가 한글로 x 축을 한글로 가~마 로 설정하고, y 축 근처에 (단위) 문구를 넣고 싶었다. 하지만 별다른 설정을 하지 않으면 아래와 같은 한글깨짐 현상을 보게 될지도 모른다. ggplot 을 쓰려는데 한글을 못쓸리 없다. 열심히 해결책을 찾아 본다.

 

우선 사전작업이 하나 있는데, 아래의 extrafont 라이브러리를 설치하고, 컴퓨터에 설치된 폰트를 불러온다.

install.packages("extrafont")
library(extrafont)
font_import()

 

그리고, 그래프를 만들 데이터를 정의한다. 

tb = tibble(x = 1:5, 
            y = c(10,15,5,25,20), 
            l = c("가", "나", "다", "라", "마")) %>% 
  mutate(z = max(y) == y)

 

ggplot 막대그래프를 별다른 설정없이 그리면, 아래와 같이 한글이 깨져서 나온다.

ggplot(tb, aes(x, y, fill = factor(z))) + 
  geom_col(width = 0.6) +
  coord_cartesian(xlim = c(.7,5.3), clip = "off") +
  scale_x_continuous(breaks = tb$x, labels = tb$l) +
  theme(axis.text.x = element_text(margin = margin(.3,0,0,0, "cm"), size = 15)) +
  annotate("text", x = 0.15, y = 28, label = "(단위)", size = 4)

하지만 폰트 설정을 하고나면, 한글이 제대로 나온다.

ggplot(tb, aes(x, y, fill = factor(z))) + 
  geom_col(width = 0.6) +
  coord_cartesian(xlim = c(.7,5.3), clip = "off") +
  scale_x_continuous(breaks = tb$x, labels = tb$l) +
  theme(axis.text.x = element_text(margin = margin(.3,0,0,0, "cm"), size = 15,
                                   family = "AppleSDGothicNeo-ExtraBold")) +
  annotate("text", x = 0.18, y = 28, label = "(단위)", size = 4,
           family = "AppleSDGothicNeo-Regular")

반응형

혹시 폰트명을 잘 모르겠다면 맥북, 아이맥 환경인 경우 폰트 정보를 알아내는 방법은 [서체관리자]에 들어가서, 서체정보를 가져오는 것이다.

 

가보면 서체명이 한글로 보일 것이다. 그렇다고 R에서 한글로 폰트정의를 할 수는 없고 다른 뷰로 보면 영문 서체명이 보이니 그걸로 R에서 폰트정의를 하면 된다. 원하는 폰트를 골라본다.

 

 

 

그렇게 해서, 한글 깨짐도 해결하고 차트색상/간격/크기 조정을 하고난 최종 결과이다. 훨씬 더 깔끔한 디자인이 되었다.

ggplot(tb, aes(x, y, fill = factor(z))) + 
  geom_col(width = 0.6) +
  coord_cartesian(xlim = c(.7,5.3), clip = "off") +
  scale_x_continuous(breaks = tb$x, labels = tb$l) +
  scale_y_continuous(expand = expansion(mult = 0), breaks = seq(0,25,5)) + 
  theme_void(base_family = "AppleSDGothicNeo-Regular") +
  theme(
    axis.line.x = element_line(size = 1.2), 
    axis.text.x = element_text(margin = margin(.3,0,0,0, "cm"), size = 20,
                               family = "AppleSDGothicNeo-ExtraBold"),
    axis.text.y = element_text(margin = margin(0,.3,0,0, "cm"), size = 15),
    panel.grid.major.y = element_line(size = 0.3, colour = "grey"),
    plot.title = element_text(margin = margin(0,0,0.7,0,"cm"), hjust = -0.09),
    plot.margin = margin(1,1,.7,1, "cm"),
    legend.position = "none"
  ) + 
  annotate("text", x = 0.15, y = 28, label = "(단위)",
           family = "AppleSDGothicNeo-Regular", size = 4) +
  scale_fill_manual(values = c("#7bccc4", "#2b8cbe"))
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
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
글 보관함