2017-03-16 15 views
0

ggplot의 facet_grid를 사용하여 차트 상단의 레이블과 플롯의 여백 사이에 공백을 추가하는 방법이 있습니까? 아래는 재현 가능한 예제입니다.r ggplot2 facet_grid 차트 상단과 테두리 사이에 공백을 추가하는 방법

library(dplyr) 
library(ggplot2) 
Titanic %>% as.data.frame() %>% 
filter(Survived == "Yes") %>% 
mutate(FreqSurvived = ifelse(Freq > 100, Freq*1e+04,Freq)) %>% 
ggplot(aes(x = Age, y = FreqSurvived, fill = Sex)) + 
geom_bar(stat = "identity", position = "dodge") + 
facet_grid(Class ~ ., scales = "free") + 
theme_bw() + 
geom_text(aes(label = prettyNum(FreqSurvived,big.mark = ",")), vjust = 0, position = position_dodge(0.9), size = 2) 

결과 차트에는 플롯 테두리 바로 옆에 숫자 레이블이 있습니다.

picture

답변

1

한 가지 간단한 방법은 scale_y_continuous의 expand 인수를 사용하는 것입니다

dt = Titanic %>% as.data.frame() %>% 
    filter(Survived == "Yes") %>% 
    mutate(FreqSurvived = ifelse(Freq > 100, Freq*1e+04,Freq)) 

ggplot(dt, aes(x = Age, y = FreqSurvived, fill = Sex)) + 
    geom_bar(stat = "identity", position = "dodge") + 
    facet_grid(Class ~ ., scales = "free") + 
    theme_bw() + 
    geom_text(aes(label = prettyNum(FreqSurvived,big.mark = ",")), 
      vjust = 0, position = position_dodge(0.9), size = 2) + 
    scale_y_continuous(expand = c(0.1,0)) 

enter image description here

expand 사용의 단점은 위 막대 아래 두 공간을 추가하는 것입니다 . 또 다른 방법은 바 위에있는 높이의 그래프에 보이지 않는 데이터를 플롯하여 ggplt가 더미 데이터를 수용 할 수 있도록 축 범위를 확장하도록하는 것입니다. (`이 경우 '각각 Y 축 0.1 * y_range + 0'에 추가 expand` :

Titanic %>% as.data.frame() %>% 
    filter(Survived == "Yes") %>% 
    mutate(FreqSurvived = ifelse(Freq > 100, Freq*1e+04,Freq)) %>% 
    ggplot(aes(x = Age, y = FreqSurvived, fill = Sex)) + 
    geom_bar(aes(y = FreqSurvived*1.2), stat = "identity", 
      position = "dodge", fill=NA) + 
    geom_bar(stat = "identity", position = "dodge") + 
    facet_grid(Class ~ ., scales = "free") + 
    theme_bw() + 
    geom_text(aes(label = prettyNum(FreqSurvived,big.mark = ",")), 
      vjust = 0, 
      position = position_dodge(0.9), size = 2) 

enter image description here

+0

조금 정교한 : 여기서 I는 높이가 1.2 * 실제 바 일부 보이지 않는 바 추가 기본값은 c (0.05, 0)입니다. – GGamba