2017-03-16 80 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

一個簡單的方法是使用expand說法scale_y_continuous的:

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擴展軸範圍以容納這個虛擬數據。在這裏,我添加一些看不見的條,其高度爲1.2 *實際柱:

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

要詳細一點:'expand'在這種情況下'0.1 * y_range + 0'到每個y軸添加(默認是c(0.05,0)), – GGamba

相關問題