R ggplot2 geom_boxplot分析器无法用于自定义分组器

时间:2017-11-21 19:37:21

标签: r ggplot2 boxplot

我正在尝试在geom_boxplot中使用group =选项,它适用于一个分组功能,但不适用于另一个分组功能。第一个地块运行,第2和第3个地块(实际上相同,称为不同)都未能产生2017年前的2个月箱图和2017年的1个月箱图,正如石斑鱼的意图。对于石斑鱼功能,ggplot声明警告消息:position_dodge需要非重叠的x区间" ,但X值在图表中是相同的。显然与我的groupdates函数有关,但组似乎是正确构造的。建议欢迎。谢谢。

library(tidyverse)
library(lubridate)
# I want two month groups before 2017, and one-month groups in 2017

groupdates <- function(date) {
  month_candidate <-case_when(
    year(date) < 2017 ~ paste0(year(date), "-", (floor(((0:11)/12)*6)*2)+1),
    TRUE ~ paste0(year(date), "_", month(date))
  )
  month_candidate2 <-case_when(
    (str_length(month_candidate)==6) ~ paste0(str_sub(month_candidate,1,5), "0", str_sub(month_candidate,6)),
    TRUE ~ month_candidate
  )
  return(month_candidate2)
}

generate_fake_date_time <- function(N, st="2015/01/02", et="2017/02/28") {
       st <- as.POSIXct(as.Date(st))
       et <- as.POSIXct(as.Date(et))
       dt <- as.numeric(difftime(et,st,unit="sec"))
       ev <- sort(runif(N, 0, dt))
       rt <- st + ev
}

n=5000
set.seed(250)
test <-as.data.frame(generate_fake_date_time(n))
colnames(test) <- "posixctdate"
test$ranvalue <- month(test$posixctdate)+runif(length(test), 0,1)
test$grouped_time <-groupdates(test$posixctdate)
table(test$grouped_time)

ggplot(test)+geom_boxplot(aes(x=posixctdate, y=ranvalue, group=paste0(year(posixctdate), "_", month(posixctdate))))
#ggplot(test)+geom_violin(aes(x=posixctdate, y=ranvalue, group=junk))
ggplot(test)+geom_boxplot(aes(x=posixctdate, y=ranvalue, group=grouped_time))
ggplot(test)+geom_boxplot(aes(x=posixctdate, y=ranvalue, group=groupdates(posixctdate)))

    sessionInfo()

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,您应该考虑修改groupdates功能。

我只使用以下方法修改了第3行:

  • ceiling代替floor
  • month(date)代替0:11

导致:

groupdates <- function(date) {
    month_candidate <-case_when(
        year(date) < 2017 ~ paste0(year(date), "-", (ceiling(((month(date))/12)*6)*2)+1),
        TRUE ~ paste0(year(date), "_", month(date))
    )
    month_candidate2 <-case_when(
        (str_length(month_candidate)==6) ~ paste0(str_sub(month_candidate,1,5), "0", str_sub(month_candidate,6)),
        TRUE ~ month_candidate
    )
    return(month_candidate2)
}

我还修改了ranvalue的计算以获得更好的分布,我打赌你想使用nrow代替length

test$ranvalue <- month(test$posixctdate) + runif(nrow(test), 0, 1)
test$grouped_time <-groupdates(test$posixctdate)
table(test$grouped_time)

输出(无变化):

ggplot(test)+geom_boxplot(aes(x=posixctdate, y=ranvalue, group=grouped_time))

plot