“错误:无效输入:time_trans仅适用于POSIXct类的对象”,具有geom_rect和date / POSIXct类型

问题描述 投票:0回答:1

我有如下数据集:

# A tibble: 30 x 4
# Groups:   Group, Week_End_Date [30]
   Group Week_End_Date       time_period             Outcome
   <lgl>   <dttm>              <fct>                   <dbl>
 1 FALSE   2019-09-22 00:00:00 Baseline                5241.
 2 FALSE   2019-09-29 00:00:00 Baseline                5089.
 3 FALSE   2019-10-06 00:00:00 Baseline                4991.
 4 FALSE   2019-10-13 00:00:00 Baseline                4920.
 5 FALSE   2019-10-20 00:00:00 Baseline                4896.
 6 FALSE   2019-10-27 00:00:00 Baseline                4921.
 7 FALSE   2019-11-03 00:00:00 Baseline                4999.
 8 FALSE   2019-11-10 00:00:00 Activation              5003.
 9 FALSE   2019-11-17 00:00:00 Activation              4995.
10 FALSE   2019-11-24 00:00:00 Activation              5098.
# ... with 20 more rows

例如,我可以绘制图形

    ggplot(dataset, aes(y=Outcome, x=Week_End_Date, color=Group, fill=Group)) +
      geom_point() +
      geom_line() +
      theme_bw() +
labs(y="Outcome", x="Date", color="Group", fill="Group")

graph without rectangle

我想根据变量“ time_period”(Week_End_Date嵌套在此变量中)对其进行着色

例如

ggplot(dataset, aes(y=Outcome, x=Week_End_Date, color=Group, fill=Group)) +
  geom_point() +
  geom_line() +
  theme_bw()
  geom_line() +
  theme_bw() +
 geom_rect(aes(fill=time_period, xmax=Inf, xmin=-Inf, ymax=Inf, ymin=-Inf)) 

但是这会导致错误消息

Error: Invalid input: time_trans works with objects of class POSIXct only

我还尝试过分别绘制两个矩形(一旦成功绘制,我会在稍后添加alpha参数):

    ggplot(dataset, aes(y=Outcome, x=Week_End_Date, color=Group, fill=Group)) +
      geom_point() +
      geom_line() +
      theme_bw()
      geom_line() +
      theme_bw() +
geom_rect(inherit.aes=FALSE, aes(xmin=dmy("06Nov2019"), xmax=dmy("06Jan2020"), ymax=Inf, ymin=-Inf), fill="red") +
  geom_rect(inherit.aes=FALSE, aes(xmin=dmy("01Jan2019"), xmax=dmy("06Nov2019"), ymax=Inf, ymin=-Inf), fill="blue") 

但是这会导致相同的错误。

有人可以告诉我我做错了什么吗?我觉得这应该比看起来简单得多! x变量是日期时间

r ggplot2 lubridate posixct
1个回答
0
投票
我尝试模拟看起来像您的数据集的内容,但是正如@camille所说,尝试提供与您的代码一起使用的数据集?这使事情变得更快。

首先是数据:

DATES = seq(as.POSIXlt("2019-01-01 00:00:00", tz="UTC"), as.POSIXlt("2020-01-31 00:00:00", tz="UTC"), length.out=20) dataset = data.frame( Outcome = c(rpois(20,1000),rpois(20,2000)), Week_End_Date = rep(DATES,2), Group = rep(c(FALSE,TRUE),each=20) ) dataset$time_period = ifelse( dataset$Week_End_Date < as.POSIXlt("2019-11-06 00:00:00", tz="UTC"), "Baseline", "Activation" )

© www.soinside.com 2019 - 2024. All rights reserved.