【问题标题】:How to align grid and whisker of box plot with ggplot2?如何将箱线图的网格和胡须与 ggplot2 对齐?
【发布时间】:2018-04-04 16:10:27
【问题描述】:

我正在根据这个答案绘制按周数分组的每小时数据:https://stackoverflow.com/a/48196838/5235575

我的示例显示了 2016 年的前两周,从 2016 年 1 月 4 日星期一 00:00 开始,到 2016 年 1 月 17 日星期日 23:00 结束

如何将主网格和 x 轴的相应标签与箱线图的胡须对齐?

ggplot(table, aes(x=as.Date(datetime_hour), y=count_hour, group=format(as.Date(datetime_hour),"%W"))) + geom_boxplot() + scale_x_date(date_breaks = "week", date_labels="%W") + labs(x = "week number")

【问题讨论】:

    标签: r ggplot2 boxplot week-number


    【解决方案1】:

    IIUC - 只需在 aesxgroup 参数中传递计算出的周数

    ggplot(table, aes(x = format(as.Date(table$datetime_hour),"%W"), y = count_hour, 
                      group = format(as.Date(table$datetime_hour),"%W"))) + 
      geom_boxplot() + labs(x = "week number")
    

    或者,将其创建为新变量:

    table$week_num <- format(as.Date(table$datetime_hour),"%W")
    
    ggplot(table, aes(x = week_num, y = count_hour, group = week_num)) + 
      geom_boxplot() + labs(x = "week number")
    

    使用随机数据进行演示(为重现性而播种)

    set.seed(6776)
    
    table <- data.frame(
      datetime_hour = Sys.Date() - seq(30),
      count_hour = rnorm(30, mean = 100, sd = 50)
    )
    
    table$week_num <- format(as.Date(table$datetime_hour),"%W")
    
    ggplot(table, aes(x = week_num, y = count_hour, group = week_num)) + 
      geom_boxplot() + labs(x = "week number")
    

    【讨论】:

      【解决方案2】:

      不是一个完美的解决方案,但我认为问题在于将数据中的中断与图中的中断对齐。我使用了您链接到的 SO 帖子中的示例数据,并添加了一个变量,我将日期缩短为几周。这给出了一个因子,我将其用作ggplot 中的 x 输入,并使用 scale_x_discrete 用函数格式化标签。

      library(ggplot2)
      
      # From linked SO post
      
      df <- data.frame(
          value = rnorm(62), 
          my.date = seq(as.Date("2013-12-01"), as.Date("2014-01-31"), by="1 day")
          )
      
      # Cut dates into weeks
      
      df$date_brk <- cut(df$my.date, breaks = "week")
      
      ggplot(df, aes(x = date_brk, y = value)) +
          geom_boxplot() +
          scale_x_discrete(labels = function(x) format(as.Date(x), "%W")) +
          theme(panel.grid.minor.x = element_blank())
      

      reprex package (v0.2.0) 于 2018 年 4 月 4 日创建。

      使用lubridate 包可能还有更好的方法。

      【讨论】:

        猜你喜欢
        • 2015-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-14
        • 2018-02-23
        相关资源
        最近更新 更多