在 r 中为多个 y 对象制作 presence/absence 时间轴

making a presence/absence timeline in r for multiple y objects

这是我第一次使用 SO,我是 R 新手;抱歉,如果这有点基础或不清楚(或者如果问题已经得到回答......我正在努力编码并且需要非常具体的答案才能理解)

我想制作一张与此类似的图像:

除了我希望它在时间轴上水平放置,并从 x-axis 绘制两条垂直线。

我可以简单的设置数据,只有两个变量——date和Tag。

    Tag Date
1   1   1/1/2014
2   3   1/1/2014
3   1   1/3/2014
4   2   1/3/2014
5   3   1/3/2014
6   5   1/3/2014
7   2   1/4/2015
8   3   1/4/2015
9   4   1/4/2015
10  6   1/4/2015
11  1   1/5/2014
12  2   1/5/2014
13  4   1/5/2014
14  6   1/5/2014
15  1   1/6/2014
16  2   1/6/2014
17  3   1/6/2014
18  4   1/6/2014
19  6   1/6/2014
20  2   1/7/2014
21  4   1/7/2014
22  1   1/8/2014
23  2   1/8/2014
24  6   1/8/2014

这是我想要完成的绘制图像:

回顾一下 - 我想获取此数据,它显示了在某个位置检测到动物的日期,并将其绘制在时间轴上,两条垂直线表示两个日期。如果连续几天检测到动物(比如标签 2),我想用一条线连接这些日期,如果连续几天检测发生但没有检测到,一个简单的点就足够了。我想象 y-axis 与每个单独的标签堆叠在一起,而 x-axis 是一个日期刻度 - 对于每个日期,如果检测到标签 ID,则将标记其对应的 x,y 坐标;如果在特定日期未检测到标签;相应的 x,y 坐标将保持空白。

这里有一个follow-up问题:

我想为某些日期添加阴影背景。我想我可以使用 geom_rect 来使用它,但我不断收到以下错误: Error: Invalid input: date_trans works with objects of class Date only

使用你写的代码,这是我添加的接收错误的代码:

geom_rect(aes(xmin=16075, xmax=16078, ymin=-Inf, ymax=Inf), fill="red", alpha=0.25)

此代码将绘制,但不透明,因此变得相当无用: geom_rect(xmin=16075, xmax=16078, ymin=-Inf, ymax=Inf)

您首先需要将日期格式更改为 Date。然后你需要弄清楚日期是否连续。最后你需要绘制它们。下面是使用包 dplyrggplot2 的可能解决方案。

# needed packages
require(ggplot2)
require(dplyr)
# input your data (changed to 2014 dates)
dat <- structure(list(Tag = c(1L, 3L, 1L, 2L, 3L, 5L, 2L, 3L, 4L, 6L, 1L, 2L, 4L, 6L, 1L, 2L, 3L, 4L, 6L, 2L, 4L, 1L, 2L, 6L), Date = structure(c(1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 7L, 7L, 7L), .Label = c("1/1/2014", "1/3/2014", "1/4/2014", "1/5/2014", "1/6/2014", "1/7/2014", "1/8/2014"), class = "factor")), .Names = c("Tag", "Date"), class = "data.frame", row.names = c(NA, -24L))
# change date to Date format
dat[, "Date"] <- as.Date(dat[, "Date"], format='%m/%d/%Y')
# adding consecutive tag for first day of cons. measurements
dat <- dat %>% group_by(Tag) %>% mutate(consecutive=c(diff(Date), 2)==1)
# plotting command
ggplot(dat, aes(Date, Tag)) + geom_point() + theme_bw() +
  geom_line(aes(alpha=consecutive, group=Tag)) +
  scale_alpha_manual(values=c(0, 1), breaks=c(FALSE, TRUE), guide='none')