为每个 ID 绘制日期范围并使用 ggplot 标记特定日期

plotting Date ranges for each ID and marking specific Dates using ggplot

这是我的数据


mydata = data.frame (id =c(1,1,2,3,3,4,4,5,6,6,7,7,8),
                     startdate=c("2014-01-21","2015-04-01","2016-03-15","2013-01-13","2014-01-02","2017-04-05","2021-07-22","2022-03-01","2016-01-28","2016-05-05",
                                 "2015-04-16","2015-09-01","2019-01-24"),
                     enddate = c("2015-03-06","2016-01-01","2017-04-01","2013-11-11", "2014-05-06","2018-12-24","2022-02-02","2022-05-02","2016-04-07","2016-07-12","2016-02-02",
                                 "2018-08-23","2019-03-15"),
                     dx_date = c("2014-03-03","2014-03-04","2016-05-05","2013-04-04","2013-04-04","2017-06-06","2021-12-25","2021-12-25","2016-03-08",
                                 "2016-03-08","2015-07-07","2016-11-12","2016-11-12"))

我想绘制出每个 ID 的开始日期和结束日期之间的时间,我已经在下面完成了。

ggplot(mydata) + 
  geom_linerange(aes(y = id, xmin = startdate, xmax = enddate ), size = 4,
                 color = "orange") +
  xlab("date")

这给了我以下信息:

但是现在我正在尝试为图表上的每个 id 标记(可能是横跨横条的星号或垂直线)dx_date,而且我不完全确定该怎么做.我希望使用 dx_date 来做类似下面的事情(只是把它画进去)。任何帮助将不胜感激!!

您应该使用 Date 对象而不是字符串:它使 x-axis 更易于阅读,更好地显示间隙和相对时间间隙,并允许对美学进行许多其他控制。

至于额外的点,再加一个geom_point就可以了。您可以使用 scale_x_date 控制 x-axis 上的日期,我将在下面的代码中进行演示;它的使用不是必需的,在这种情况下,它会每隔一年在 x-axis.

上显示一次
mydata[c("startdate","enddate","dx_date")] <- lapply(mydata[c("startdate","enddate","dx_date")], as.Date)
ggplot(mydata, aes(y=id)) +
  geom_linerange(aes(xmin=startdate, xmax=enddate), size=4, color = "orange") +
  geom_point(aes(x=dx_date)) +
  scale_x_date(date_breaks = "1 year", date_labels = "%Y-%m")