【发布时间】:2017-11-21 19:37:20
【问题描述】:
我正在尝试使用 geom_boxplot 中的 group= 选项,它适用于一个分组功能,但不适用于另一个。第一个地块运行,第二个和第三个地块(实际上相同,称为不同)都未能产生 2017 年之前的 2 个月箱线图和 2017 年的一个月箱线图,正如石斑鱼打算的那样。对于 grouper 函数 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()
【问题讨论】:
-
这个怎么样?
ggplot(test)+geom_boxplot(aes(x=factor(grouped_time), y=ranvalue) -
是的,这会起作用,但是你会失去 X 的 datetime/posixct 质量,我最终需要在箱线图上运行 geom_smooth。
-
情节对我来说似乎是正确的。你有很大的箱线图,因为你有
posixctdate和grouped_time真的不同的行。我怀疑你的groupdates函数有错误?它期望做什么?试试ggplot(test, aes(x = posixctdate, y = grouped_time)) + geom_point()看看你有一个grouped_time值,几个posixctdate值对应全年