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

相关问题