1

有没有办法使用 ggplot 的 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)

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

图片

4

2 回答 2

9

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

expand选项实际上将允许您仅在图表顶部添加空间。从?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)))
于 2018-10-09T17:10:59.370 回答
1

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

在此处输入图像描述

使用的缺点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)

在此处输入图像描述

于 2017-03-16T22:23:19.803 回答