r ggplot2 facet_grid 如何在图表顶部和边框之间添加 space

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

有没有办法使用 ggplot 的 facet_grid 在图表顶部的标签和图表的边距之间添加 space。下面是一个可重现的例子。

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)

生成的图表在图的边界旁边有数字标签。

一种简单的方法是使用 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))

使用 expand 的缺点是它会在条的上方和下方添加 space。另一种方法是在图表上的条形上方的高度绘制一些不可见的数据,这将迫使 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)

我想添加到@dww 的答案中,但没有足够的声誉。

expand 选项实际上允许您将 space 添加到图表的顶部。来自 ?expand_scale 帮助文件:

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