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

tch*_*rty 2 r ggplot2

以下是geom_boxplot手册页中的示例:

p = ggplot(mpg, aes(class, hwy))
p + geom_boxplot(aes(colour = drv))
Run Code Online (Sandbox Code Playgroud)

看起来像这样:

在此输入图像描述

我想制作一个非常相似的图,但是(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)
)
Run Code Online (Sandbox Code Playgroud)

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

  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)
      )
    
    Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  1. 另一方面,如果我使用此处建议Date的附加group变量,则不再添加任何其他影响:color

        df_box %>% 
          ggplot(aes(
            x = Date,
            y = Value,
            group = Date, 
            color = Source
          )) + 
         geom_boxplot() + 
         theme_bw()
    
    Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

ali*_*ire 9

因为你需要单独盒的每个组合DateSource使用interaction(Source, Date)group审美:

ggplot(df_box, aes(x = Date, y = Value, 
                   colour = Source, 
                   group = interaction(Source, Date))) + 
    geom_boxplot()
Run Code Online (Sandbox Code Playgroud)

使用日期格式化x轴绘图