ggplot2:按日期(年)和组的boxplot

时间:2016-10-01 16:35:02

标签: r ggplot2

以下是geom_boxplot man page

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

看起来像这样:

enter image description here

我想制作一个非常相似的情节,但是(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)
      )
    
  2. enter image description here

    1. 另一方面,如果我使用Date作为建议here的其他group变量,则添加color不再会产生任何其他影响:< / p>

          df_box %>% 
            ggplot(aes(
              x = Date,
              y = Value,
              group = Date, 
              color = Source
            )) + 
           geom_boxplot() + 
           theme_bw()
      
    2. enter image description here

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

1 个答案:

答案 0 :(得分:7)

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

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

plot with date formatted x-axis