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

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

提问人:T K 提问时间:5/9/2022 更新时间:5/9/2022 访问量:349

问:

这是我的数据


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")

这给了我以下内容:

enter image description here

但是,现在我正在尝试标记(可能用星号或垂直线穿过条形图)图表上每个 id 的dx_date,但我不完全确定该怎么做。我想使用dx_date做如下的事情(刚刚画出来)。任何帮助将不胜感激!

enter image description here

r ggplot2 时间序列 数据操作

评论

0赞 r2evans 5/9/2022
你的“日期”是字符串,而不是日期。您是否使用或将它们从分类字符串转换为类似数字的日期对象?as.Dateas.POSIXct

答:

2赞 r2evans 5/9/2022 #1

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

至于额外的点,只需添加另一个.您可以使用 控制 x 轴上的日期,我将在下面的代码中演示;它不是必需的,在这种情况下,它将每隔一年在 x 轴上显示一次。geom_pointscale_x_date

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")

ggplot linerange with dots