【问题标题】:r ggplot how to adjust the column width of barr ggplot如何调整bar的列宽
【发布时间】:2021-04-20 16:42:55
【问题描述】:

我需要弄清楚如何根据特定变量调整绘图的宽度,而无需更改 facet_wrap 函数的 scales = "free" 参数。我尝试使用基于变量调整条形宽度的case_when,但出现错误。

以下是可重现的示例,显示了我遇到的问题。

library(tidyverse)

set.seed(1)

data.frame(date = rep(seq.Date(Sys.Date()
                       , by = "day", length.out = 10), 3)
,Time = rep(c("AM","PM"), each = 30)
,office = rep(LETTERS[1:3], 2)
,n = sample(c(50:100),60, replace = TRUE)) %>%
add_row(date = Sys.Date(), Time = "AM", office = "Z", n = 80) %>%
ggplot(aes(x = date, y = n, group = office)) +
geom_bar(stat = 'identity', position = 'stack'
         ,width = .7, show.legend = FALSE, alpha =.75) +
facet_wrap(vars(office, Time), ncol = 2, labeller = "label_both",
           scales = "free")

【问题讨论】:

    标签: r ggplot2 facet-wrap


    【解决方案1】:

    如果您没有特别要求使用facet_wrap(),则应使用facet_grid(),其中包含一个非常有用的参数:spacescales 允许每个绘图的比例根据“空”数据调整大小,space 做同样的事情,但允许您保持条形的相同整体宽度不变。

    data.frame(date = rep(seq.Date(Sys.Date()
                                   , by = "day", length.out = 10), 3)
               ,Time = rep(c("AM","PM"), each = 30)
               ,office = rep(LETTERS[1:3], 2)
               ,n = sample(c(50:100),60, replace = TRUE)) %>%
      add_row(date = Sys.Date(), Time = "AM", office = "Z", n = 80) %>%
      ggplot(aes(x = date, y = n, group = office)) +
      geom_bar(stat = 'identity', position = 'stack'
               ,width = .7, show.legend = FALSE, alpha =.75) +
      facet_grid(office ~ Time, labeller = "label_both",
                 scales = "free", space='free')
    

    我确实希望 facet_wrap()space 作为参数,但可惜,目前情况并非如此。如果您需要将构面全部放在一行或一列中,可以使用 ggforce 包中的 facet_row()facet_col()。它们允许使用 space 参数,但仅限于一行或一列(不换行)。

    【讨论】:

      猜你喜欢
      • 2018-02-02
      • 2023-03-26
      • 2019-11-08
      • 2018-07-30
      • 2021-06-06
      • 2017-04-06
      • 2020-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多