I am looking to create a plot in R where the y-axis represents unique id
values, and the x-axis is a timeline. Each id
should be represented by a line segment connecting two points: a start
date and an end
date. Below is an example dataset:
id<-c("id1","id2","id3")
start<-c("2010-02-01","2010-04-05","2010-03-08")
end<-c("2013-11-10","2013-01-01","2011-05-07")
data<-data.frame(id,start,end)
I need assistance with code or guidance on how to create this plot, with each id
having its own line segment between its respective start
and end
dates. Any help or suggestions on how to approach this task would be greatly appreciated!
You can do this manually in base R by first creating a blank plot them adding in segments
. I also added in points
to distinguish the ends. You can play around with the parameters to tweak the look to exactly what you want:
plot(range(data$start, data$end), c(1, nrow(data)),
type = "n", xlab = "", ylab = "", axes = FALSE)
segments(x0 = data$start, x1 = data$end, y0 = 1:nrow(data), lwd = 3)
points(x = c(data$start, data$end), y = rep(1:nrow(data), 2), pch = 20, cex = 3)
axis(1, at = seq.Date(min(data$start), max(data$end), by = "month"),
labels = seq.Date(min(data$start), max(data$end), by = "month"))
axis(2, at = 1:nrow(data), labels = data$id)
You may also be interested in the vistime
package (but I personally find it a bit easier to control specifics in the above approach):
vistime::vistime(data)