【发布时间】:2020-05-03 09:15:44
【问题描述】:
我有一个数据集如下:
# 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")
我想根据变量“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 变量是一个日期时间
【问题讨论】:
-
你能share your data set吗?还是其中的一小部分?
-
谢谢,我刚刚更新了帖子以显示数据集的前 10 行。
-
如果显示两个组对问题很重要(我不知道是否是...),您应该在包含的数据样本中包含它们的一些示例 - 现在你只是有错误。 @Nate 发布的链接有几个关于如何以可重现的方式包含数据的建议
标签: r ggplot2 lubridate posixct