I am new to ggplot
library. And trying to draw the plot using the following data.frame
:
library(tidyverse)
df <-
tribble(~event, ~startdate,~enddate,~loc,
"A",as.POSIXct("1984/02/10"),as.POSIXct("1987/06/10"),"1",
"B",as.POSIXct("1984/02/11"),as.POSIXct("1990/02/12"),"2",
"A",as.POSIXct("1992/05/15"),as.POSIXct("1999/06/15"),"3",
"C",as.POSIXct("2003/08/29"),as.POSIXct("2015/08/29"),"4",
"B",as.POSIXct("2002/04/11"),as.POSIXct("2012/04/12"),"5",
"E",as.POSIXct("2000/02/10"),as.POSIXct("2005/02/15"),"6",
"A",as.POSIXct("1985/02/10"),as.POSIXct("1987/06/10"),"7",
"B",as.POSIXct("1989/02/11"),as.POSIXct("1990/02/12"),"8",
"A",as.POSIXct("1997/05/15"),as.POSIXct("1999/06/15"),"9",
"C",as.POSIXct("2010/08/29"),as.POSIXct("2015/08/29"),"10",
"B",as.POSIXct("2010/04/11"),as.POSIXct("2012/04/12"),"11",
"E",as.POSIXct("2004/02/10"),as.POSIXct("2005/02/15"),"12")
max_date = max(df$startdate,df$enddate)
Using the following code snippet:
ggplot(df)+
geom_segment(aes(y=loc, yend = loc, x = startdate, xend = enddate, colour=event),size = 5,alpha=0.6) +
geom_label(aes(label=event, y = loc, x=max_date), size=2) +
xlab("Year") + ylab("LoC") +
scale_x_datetime(date_breaks = "year", date_labels = "%Y") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
facet_grid(rows = vars(event), scales = "free")
It generates the following plot:
I would like to order the LoC axis i.e primary Y-axis within the label i.e. event (secondary Y-axis). Within each label, it should print a point on the primary Y-axis in ascending order (For event C (4 -> 10) and E(6 -> 10) are already in ascending order). How can I order the other points in ascending order within each label i.e. event (I tried to sort data using order
and fct_inorder
from forcats
library but couldn't able to achieve the desired result as shown below)? How can I print a single label within each group?
Please feel free to correct me!
Any help would be great! Thank you!