2016-10-01 39 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