Here is my data
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"))
I would like to plot out the time between start and end date for each ID, which I have done below.
ggplot(mydata)
geom_linerange(aes(y = id, xmin = startdate, xmax = enddate ), size = 4,
color = "orange")
xlab("date")
Which gives me the following:
However now i m trying to mark (with maybe a star or a vertical line across the bar) the dx_date for each id on the graph as well,and Im not entirely sure how to do about doing this. Im looking to do something like the below (just drew it in) using the dx_date. Any help would be greatly appreciated!!
CodePudding user response:
You should use Date
objects instead of strings: it makes the x-axis a lot easier to read, better shows gaps and relative time gaps, and allows many other controls over the aesthetics.
As for the additional dots, just add another geom_point
. You can control the dates on the x-axis using scale_x_date
, which I'll demo in the code below; it's use is not required, and in this case it would show every other year on the 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")