Search code examples
rggplot2facet-grid

r ggplot2 facet_grid how to add space between the top of the chart and the border


Is there a way to add space between the labels on the top of the chart and the margin of a plot using ggplot's facet_grid. Below is a reproducible example.

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)

The resulting chart has the label of numbers right next to the border of the plot.

picture


Solution

  • One simple way is to use the expand argument of 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

    The downside of using expand is that it will add space both above and below the bars. An alternative is to plot some invisible data on the graph at a height above the bars, which will force ggplt to expand the axis ranges to accomodate this dummy data. Here I add some invisible bars whose height is 1.2* the actual bars:

    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