简体   繁体   中英

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.

图片

I wanted to add to @dww 's answer, but don't have enough reputation.

The expand option actually will allow you to add space only to the top of your graph. From the ?expand_scale help file:

# No space below the bars but 10% above them
ggplot(mtcars) +
  geom_bar(aes(x = factor(cyl))) +
  scale_y_continuous(expand = expand_scale(mult = c(0, .1)))

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))

在此处输入图片说明

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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM