2016-10-01 64 views
1

这里箱线图是从geom_boxplot man page一个例子:GGPLOT2:按日期(yearmon)和组

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轴:

    ​​

enter image description here

  • 在另一方面,如果使用Date作为附加group变量作为建议here,加入color不再有任何额外的冲击:

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

    任何想法如何实现的#1 WHI输出le仍然保持yearmon比例x轴?

    +0

    你可以使用磨制的,而不是颜色,例如'ggplot(df_box,aes(x = Date,y = Value,group = factor(Date)))+ geom_boxplot()+ facet_wrap(〜Source)' – alistaire

    +0

    @alistaire感谢您的建议。我确实尝试过,但是它们并排比较分布是最容易的,特别是当箱型图中有多少个组件比较时。 – tchakravarty

    +0

    如果你喜欢,你可以垂直面对'facet_grid'。尽管如此,我想通过使用'Source'和'Date'作为'group'审美的交互方式来实现它:'ggplot(df_box,aes(x = Date,y = Value,color = Source,group = interaction(Source,Date)))+ geom_boxplot()' – alistaire

    回答

    4

    因为你需要单独的盒子为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

    +0

    完美,谢谢。 – tchakravarty