Consider example dataframe as:
df <- data.frame(Names = c("A", "A", "B", "B", "C", "C"),
Start = structure(c(18659, NA, 19024, NA, 19297, NA), class = "Date"),
End = structure(c(NA, 21062, NA, 20970, NA, 22552), class = "Date"),
Dates = structure(c(18659, 21062, 19024, 20970, 19297, 22552), class = "Date"))
I want to create a timeline plot with the Names
on y-axis and Dates
on x-axis. then I want to draw horizontal lines between the Start
and End
points:
ggplot(df, aes(x = Dates, y = Names)) geom_point(size = 1)
theme_classic() guides(color = FALSE) labs(title = "title")
theme(axis.line.y = element_blank(), axis.ticks = element_blank(),
axis.title = element_blank(), axis.text.y = element_text(size = 12, color = "black"),
plot.title = element_text(size = 20, hjust = 0.5, face = "bold",
margin = margin(c(0.3,0,0.5,0), unit = "in")),
axis.text.x = element_text(size = 12, color = "black",
margin = margin(c(0.27,0,0,0), unit = "in")),
axis.line.x = element_line(size = 0.9, color = "navy"))
scale_x_date(date_break = "5 months", date_labels = "%b")
geom_segment(aes(x = Start, xend = End,
y = Names, yend = Names), size = 0.6, color = "navy")
But I cannot get the horizontal segment lines to show on the plot:
Desired output is:
CodePudding user response:
You're looking for geom_linerange
. Also, your dataframe is not ideally constructed, you should fill NAs.
df <- data.frame(Names = c("A", "A", "B", "B", "C", "C"),
Start = structure(c(18659, NA, 19024, NA, 19297, NA), class = "Date"),
End = structure(c(NA, 21062, NA, 20970, NA, 22552), class = "Date"),
Dates = structure(c(18659, 21062, 19024, 20970, 19297, 22552), class = "Date")) %>%
fill(Start) %>%
fill(End, .direction = "up")
ggplot(df, aes(x = Dates, y = Names)) geom_point(size = 1)
geom_linerange(aes(xmin = Start, xmax = End))
scale_x_date(date_break = "5 months", date_labels = "%b")