如何将箱形图的网格和晶须与 ggplot2 对齐?

How to align grid and whisker of box plot with ggplot2?

我正在根据以下答案绘制按周数分组的每小时数据:

我的示例显示了 2016 年的前两周,从星期一 01-04-2016 00:00 到星期日 01-17-2016 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")

IIUC - 只需在 xgroup 参数中传递计算出的 week number aes:

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")

这不是一个完美的解决方案,但我认为问题在于将数据中的中断与绘图中的中断对齐。我使用了您链接到的 SO post 中的示例数据,并添加了一个变量,我将日期缩短为数周。这给出了一个因子,我将其用作 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-04-04。

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