Home > other >  Connect segment lines with ggplot
Connect segment lines with ggplot

Time:04-02

I'm trying to draw a bus schedule diagram with ggplot. On the X axis I want bus stops and on the Y axis I want time. I'm nearly there, but I can't find the way to make a horizontal line between each travel. Here's my plot and the dataframe.

ggplot(dat,
       aes(x = from,
           xend = to,
           y = departure,
           yend = arrival,
           ))  
  geom_segment() 
  geom_line()

tibble::tribble(
              ~from, ~to, ~departure,   ~arrival,
                "a", "b", "01:00:00", "02:00:00",
                "b", "a", "02:10:00", "03:10:00",
                "a", "b", "03:20:00", "04:20:00",
                "c", "b", "02:30:00", "03:15:00",
                "b", "c", "03:35:00", "04:30:00",
                "c", "b", "04:40:00", "05:30:00"
              )

enter image description here

CodePudding user response:

One option would be to use dplyr::lead to prepare a dataset containing the coordinates of the connecting segments like so:

library(ggplot2)
library(dplyr)
library(tidyr)

hlines <- df |> 
  mutate(departure = ifelse(lead(from) == to, lead(departure), NA),
         from = to) |> 
  tidyr::drop_na()

ggplot(df, aes(x = from, xend = to, y = departure, yend = arrival))  
  geom_segment()  
  geom_segment(data = hlines) 

  • Related