0

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

0

1 Answer 1

3

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) 

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.