【问题标题】:r ggplot2 facet_grid how to add space between the top of the chart and the borderr ggplot2 facet_grid 如何在图表顶部和边框之间添加空间
【发布时间】:2017-08-08 07:34:52
【问题描述】:

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

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

【问题讨论】:

    标签: r ggplot2 facet-grid


    【解决方案1】:

    我想添加到@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)))
    

    【讨论】:

    • expand_scale 现在已弃用;请改用expansion。相同的功能和参数。这个答案是一个完美的解决方案。
    【解决方案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 的缺点是它会在条形上方和下方增加空间。另一种方法是在图表上的条形上方高度绘制一些不可见的数据,这将迫使 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)
    

    【讨论】:

    • 详细说明:expand 在这种情况下将0.1 * y_range + 0 添加到每个 y 轴(默认为 c(0.05, 0)),
    猜你喜欢
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    • 2012-04-22
    • 2019-04-29
    • 1970-01-01
    • 2014-06-22
    相关资源
    最近更新 更多