【问题标题】:Separate boxes for two grouping variables when color by only one variable当仅由一个变量着色时,两个分组变量的分隔框
【发布时间】:2021-08-04 22:45:55
【问题描述】:

这是来自geom_boxplot man page 的示例:

p = ggplot(mpg, aes(class, hwy))
p + geom_boxplot(aes(colour = drv))

看起来像这样:

我想制作一个非常相似的图,但使用(yearmon 格式化)日期,class 变量在示例中,而因子变量drv 在示例中。

这里是一些示例数据:

df_box = data_frame(
  Date = sample(
    as.yearmon(seq.Date(from = as.Date("2013-01-01"), to = as.Date("2016-08-01"), by = "month")),
    size = 10000, 
    replace = TRUE
  ),
  Source = sample(c("Inside", "Outside"), size = 10000, replace = TRUE),
  Value = rnorm(10000)
)

我尝试了很多不同的东西:

  1. 在日期变量周围放置一个as.factor,然后我不再有 x 轴的间隔很好的日期刻度:

        df_box %>% 
          ggplot(aes(
          x = as.factor(Date),
        y = Value,
        # group = Date, 
        color = Source
      )) + 
      geom_boxplot(outlier.shape = NA) + 
      theme_bw() + 
      xlab("Month Year") + 
      theme(
        axis.text.x = element_text(hjust = 1, angle = 50)
      )
    

  1. 另一方面,如果我按照建议的hereDate 用作附加的group 变量,则添加color 不再有任何附加影响:

        df_box %>% 
          ggplot(aes(
            x = Date,
            y = Value,
            group = Date, 
            color = Source
          )) + 
         geom_boxplot() + 
         theme_bw()
    

关于如何在保持yearmon 缩放 x 轴的同时实现 #1 的输出的任何想法?

【问题讨论】:

  • 您可以使用刻面而不是颜色,例如ggplot(df_box, aes(x = Date, y = Value, group = factor(Date))) + geom_boxplot() + facet_wrap(~Source)
  • @alistaire 感谢您的建议。我确实尝试过,但是当它们并排时比较分布是最容易的,尤其是当要比较的组件与箱线图中的组件一样多时。
  • 如果您愿意,可以使用facet_grid 垂直切面。不过,我想出了如何按照您的方式进行操作,方法是使用 SourceDate 的交互作为 group 美学:ggplot(df_box, aes(x = Date, y = Value, colour = Source, group = interaction(Source, Date))) + geom_boxplot()

标签: r ggplot2 boxplot


【解决方案1】:

由于DateSource 的每个组合都需要单独的框,因此请使用interaction(Source, Date) 作为group 美学:

ggplot(df_box, aes(x = Date, y = Value, 
                   colour = Source, 
                   group = interaction(Source, Date))) + 
    geom_boxplot()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    • 1970-01-01
    • 2013-09-14
    • 2021-02-12
    相关资源
    最近更新 更多